如果要检查用户是否已经滚动到页面底部,可以使用 scroll() jQuery 事件。
在窗口上使用 scroll() 事件:
<!DOCTYPE HTML> <html> <head> <title>文档的标题</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> body { text-align: center; } h2 { color: green; } </style> </head> <body> <h1> Scroll </h1> <div class="div"> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> </div> <script> $(window).on('scroll', function() { if($(window).scrollTop() >= $('.div').offset().top + $('.div').outerHeight() - window.innerHeight) { alert('Bottom'); } }); </script> </body> </html>
给定的代码获取窗口的顶部滚动,因此页面向下滚动多少,它添加可见窗口的高度并检查它是否等于文档的高度。
要检查用户是否靠近底部,请运行以下命令:
<!DOCTYPE HTML> <html> <head> <title>文档的标题</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> body { text-align: center; } h1 { color: blue; } </style> </head> <body> <h1> Scroll </h1> <div class="div"> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> <h2>Text</h2> </div> <script> $(window).scroll(function() { if($(window).scrollTop() + $(window).height() > $(document).height() - 100) { alert("Near bottom!"); } }); </script> </body> </html>
scroll() 方法或者触发滚动事件,或者添加一个函数以在发生滚动事件时调用。
scroll() 事件
当用户滚动到元素中的不同位置时,将向元素发送滚动事件。
它适用于窗口对象(浏览器窗口)、可滚动框架以及 CSS 溢出属性设置为“滚动”或者“自动”的元素。
日期:2020-06-02 22:16:11 来源:oir作者:oir