0

这是简化的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 根本不滚动(初始位置)时,滚动条顶部带有三角形符号的小按钮不会触发事件。也许这是合乎逻辑的,但我寻找一种解决这种行为的方法,因为这是目前解决启用拖放的 dojo 框架树小部件的唯一方法。是的,我知道,解决方法。

4

1 回答 1

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;">&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. 基本上,它确保用户永远不会完全滚动到顶部或底部,从而确保始终存在滚动事件。

于 2012-05-05T13:42:04.517 回答