gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:07:27 24 4
gpt4 key购买 nike

示例如下: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>

请注意,当您将“Drag me..”文本拖动到项目列表顶部/底部附近时,列表将自动滚动。

通常这种行为很有用,因为您可以查看所需的放置区域,但有时根本不需要这样做。

是否有纯 JS 方法可以在 Chrome 47+ 中禁用该行为?我尝试在不同的元素上使用“dragover”、“mouseover”、“scroll”等,但没有成功。

最佳答案

我能够通过存储滚动的当前位置来完成此操作,并且当引发滚动事件时,我将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

关于javascript - 在可滚动容器上拖动时防止自动滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com