javascript - onscroll 事件和滚动条按钮

标签 javascript scroll dom-events

这是简化的 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/

相关文章:

javascript - 如何在其他 grunt 任务中使用 grunt-folder-list 生成的结果

使用递归的Javascript Flood填充算法

javascript - JS 函数名干扰对象属性

c++ - 如何在 QMainWindow 中按下 Ctrl 时禁用滚动功能

c++ - 在 MFC 中实现缩放控件

javascript - 如何在传单上加载 json 文件并设置样式?

javascript - 类苹果网站逐节滚动行为

javascript - 以编程方式触发 onclick 事件?

javascript - 如何在其他标签的 <a> 标签上创建相同的鼠标悬停行为?

javascript - Greasemonkey 弹出循环不等待加载事件监听器