我使用此代码检查用户是否已滚动到底部代码,但它在Google Chrome浏览器上不起作用,但在Microsoft Edge上成功运行。
在Google Chrome浏览器中,当我滚动到底部并再次滚动到顶部时,它可以工作,但我不知道为什么。
这是我正在使用的代码。
<script>
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
}
});
</script>
<!decotype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div style="height: 4000px">Scroll down!</div>
</body>
</html>
答案 0 :(得分:0)
假设您使用div加载了一些数据...(由于#load_data
)
您需要滚动获取3个值:
div
高度div
可滚动高度最后一个是 real 元素高度的element property,包括其溢出量。
此外,您需要在底部附近定义...。以像素为单位。
所以...在下面的示例中,我正在伪造一个Ajax请求。只需查找所需的代码。
$(document).ready(function() {
// Function to replace Ajax in this demo.
function createContent(n){
var fakeContent = "";
for(i=0;i<n;i++){
fakeContent += i+"<br>";
}
$("#load_data").append(fakeContent);
}
// Simulate initial content...
createContent(100);
// The code you need
var near = 20; // pixels buffer yet to be scrolled when the Ajax triggers.
$("#load_data").on("scroll",function(){
if( $(this).scrollTop() + $(this).height() + near > this.scrollHeight ){
console.log("Faking Ajax...");
createContent(50);
}
});
}); // END ready
#load_data{
height: 150px;
width: 300px;
border: 1px solid grey;
overflow-y:scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
There is 100 (0-99) lines on load.<br>
<div id="load_data"></div>
答案 1 :(得分:0)
问题是,当您使用边距(顶部或底部)时,应使用.outerHeight(true)
而不是.height
或这种情况下的高度和边距之和。如果您有填充是相同的问题。
$(window).scroll(function(){
if($(window).scrollTop()+$(window).height()>$("h3").outerHeight( true ) ){
alert("bottom!")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<h3 style="margin-top:2000px">hello world</h3>
</body>
<html>
关于.outerHeight()
获取当前计算的外部高度(包括填充,边框和 匹配集中的第一个元素(可选) 元素或设置每个匹配元素的外部高度
。