这是简化的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;"> </div>
</div>
</body>
</html>
问题是,当div根本没有滚动(初始位置)时,滚动条顶部带有三角形符号的小按钮不会触发事件。也许这是合乎逻辑的,但我搜索一种方法来解决这种行为,因为这是现在解决dojo框架树小部件并启用了拖放操作的唯一方法。是的,我知道,解决方法的解决方法。
答案 0 :(得分:2)
嗯,它不漂亮,但这应该可以解决问题:
<!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;"> </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
。基本上,它确保用户永远不会完全滚动到顶部或底部,确保始终存在滚动事件。