在可滚动容器上拖动时防止自动滚动

Prevent auto scroll while dragging over a scrollable container

本文关键字:滚动 拖动      更新时间:2023-09-26

此处的示例:http://codepen.io/eliseosoto/pen/YqxQKx

const l = document.getElementById('scrollableList');
const item3 = document.getElementById('item3');
l.addEventListener('mouseover', function(e) {
  e.stopPropagation();
  e.preventDefault();
  console.log('mouseover', e.target);
});
item3.addEventListener('dragenter', function(e) {
  e.stopPropagation();
  e.preventDefault();
  console.log('dragenter', e.target);
});
l.addEventListener('dragover', function(e) {
  console.log('xxx');
  e.stopPropagation();
  e.preventDefault();
});
l.addEventListener('scroll', function(e) {
  console.log('scroll!', e);
  e.stopPropagation();
  e.preventDefault();
});
item3.addEventListener('dragover', function(e) {
  console.log('dragover item3');
  e.stopPropagation();
  e.preventDefault();
});
#container {
  background-color: lightblue;
}
#scrollableList {
  height: 50px;
  background-color: green;
  overflow: auto;
}
<div id="container">
  <br>
  <div id="scrollableList">
    <div>Item 1</div>
    <div>Item 2</div>
    <div id="item3">Item 3</div>
    <div>Item 4</div>
    <div>Item 5</div>
    <div>Item 6</div>
    <div>Item 7</div>
    <div>Item 8</div>
    <div>Item 9</div>
    <div>Item 10</div>
    <div>Item 11</div>
    <div>Item 12</div>
    <div>Item 13</div>
    <div>Item 14</div>
  </div>
  <br>
  <div id="dragMe" draggable="true">Drag me near the top/bottom of the Item list.</div>
</div>

请注意,当您拖动项目列表顶部/底部附近的"拖动我…"文本时,该列表将自动滚动。

通常,这种行为是有用的,因为您可以将所需的放置区域放在视图中,但有时这根本不是所需的。

有没有一种纯粹的JS方法可以在Chrome 47+中禁用这种行为?我在不同的元素上尝试了"拖动"、"鼠标悬停"、"滚动"等,但都无济于事。

我可以通过存储滚动的当前位置来实现这一点,当滚动事件发生时,我将scrollTop设置为之前存储的位置。

const list = document.getElementById('scrollableList');
const dragMe = document.getElementById('dragMe');
var scrollPosition = 0;
dragMe.addEventListener('dragstart', function(e) {
  scrollPosition = list.scrollTop;
  list.addEventListener('scroll', preventDrag);
});
dragMe.addEventListener('dragend', function(e) {
  list.removeEventListener('scroll', preventDrag);
});
function preventDrag(e) {
    list.scrollTop = scrollPosition;
};

很奇怪你不能取消滚动事件。

http://codepen.io/cgatian/pen/JXZjOB?editors=1010