• JS scroll事件:页面滚动

    在 JavaScript 中,scroll 事件用于在浏览器窗口内移动文档的位置时触发,如通过键盘箭头键、翻页键或空格键移动稳定位置,或者通过滚动条滚动稳定位置。利用该事件可以跟踪文档位置变化,及时调整某些元素的的显示位置,确保它始终显示在屏幕可见区域内中。

    示例

    在下面示例中,控制红色小盒子始终位于窗口内坐标为(100px,100px)的位置。

    <div id="box"></div>
    <script>
        var box = document.getElementById("box");
        box.style.position = "absolute";
        box.style.backgroundColor = "red";
        box.style.width = "200px";
        box.style.height = "160px";
        window.onload = f;  //页面初始化时固定其位置
        window.onscroll = f;  //当文档位置发生变化时重新固定其位置
        function f(){  //元素位置固定函数
            box.style.left = 100 + parseInt(document.body.scrollLeft) + "px";
            box.style.top = 100 + parseInt(document.body.scrollTop) + "px";
        }
    </script>
    <div style="height:2000px;width:2000px;"></div>

    还有一种方法,就是利用 settimeout() 函数实现每间隔一定时间校正一次元素的位置,不过这种方法的损耗比较大,不建议使用。

更多...

加载中...