拖动可滚动容器时阻止自动滚动

时间:2016-04-19 00:04:57

标签: javascript google-chrome javascript-events

此处示例: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+中禁用该行为?我尝试在不同的元素上使用'dragover','mouseover','scroll'等无效。

1 个答案:

答案 0 :(得分:0)

我能够通过存储滚动的当前位置来实现这一点,当引发滚动事件时,我将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