gpt4 book ai didi

javascript - onscroll 事件和滚动条按钮

转载 作者:行者123 更新时间:2023-12-02 19:40:21 29 4
gpt4 key购买 nike

这是简化的 html:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function handle() { console.log("fired"); };
</script>
</head>
<body>
<div style="width:200px; height:100px; overflow-y: scroll; border: 1px solid gray;" onscroll="handle()">
<div style="width:150px; height:400px;">&nbsp;</div>
</div>
</body>
</html>

问题是,当 div 根本没有滚动(初始位置)时,滚动条顶部带有三 Angular 形符号的小按钮不会触发事件。也许这是合乎逻辑的,但我寻找一种方法来解决此行为,因为这是目前使用启用的拖放功能来解决 dojo 框架树小部件的唯一方法。是的,我知道,解决方法的解决方法。

最佳答案

嗯,这不太漂亮,但这应该可以解决问题:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function handle() { console.log("fired"); };
</script>
</head>
<body>
<div id="div" style="width:200px; height:100px; overflow-y: scroll; border: 1px solid gray;">
<div style="width:150px; height:400px;">&nbsp;</div>
</div>
<script>

//Get the element
var div = document.getElementById("div");

var ignore = true;

//Set the scroll to 1 (this will allow it to scroll up)
div.scrollTop = 1;


div.addEventListener("scroll", function(){

//Ignore generating output if the code set the scroll position
if(ignore) {
ignore = !ignore;
return;
}



//CODE GOES HERE
handle();


//If the scroll is at the top, go down one so that the user
//is still allowed to scroll.
if(div.scrollTop <= 1) {
ignore = true;
div.scrollTop = 1;
}

//If the scroll is at the bottom, go up one so the user can
//still scroll down
else if(div.scrollTop >= div.scrollHeight-div.clientHeight - 1) {
ignore = true;
div.scrollTop = div.scrollHeight-div.clientHeight - 1;
}

}, true);
</script>
</body>
</html>

我删除了内联函数调用,并将其替换为 eventListener。基本上,它确保用户永远不会完全滚动到顶部或底部,从而确保始终存在滚动事件。

关于javascript - onscroll 事件和滚动条按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10462246/

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