我有一个代码,可以在滚动到达底部之前到达 300px 时显示一些内容!当到达底部时,我想在离开底部后到达 300px 时摆脱此消息!
当我到达底部之前 300 像素时,它完美地工作,但当我尝试向后滚动 300 像素时,它不起作用。
document.addEventListener('scroll', function(event) {
var docHeight = $(document).height(); // Document height
var winHeight = $(window).height(); // Window height
var minHeight = docHeight - winHeight; // Real document height
var curHeight = $(window).scrollTop(); // Display the height according to scrolling
$(window).scroll(function() {
//BEFORE
if(curHeight + 300 > minHeight) {
document.getElementById('copyrights').innerHTML = "Welcome to bottom";
}
//AFTER (doesn't work)
if(curHeight - 300 == minHeight - 300) {
document.getElementById('copyrights').innerHTML = "Good bye";
}
});
});
最佳答案
你必须设置一个标志变量来保存你之前是否已经到达底部的状态,否则它只会在页面加载时说再见。另外,第二个检查应该是 if (curHeight <= minHeight - 300)。总而言之,如下所示:
var scrolledToBottom = false;
document.addEventListener('scroll', function(event) {
var docHeight = $(document).height(); // Document height
var winHeight = $(window).height(); // Window height
var minHeight = docHeight - winHeight; // Real document height
var curHeight = $(window).scrollTop(); // Display the height according to scrolling
$(window).scroll(function() {
//BEFORE
if(curHeight + 300 > minHeight) {
document.getElementById('copyrights').innerHTML = "Welcome to bottom";
scrolledToBottom = true;
}
if (scrolledToBottom) {
//AFTER (doesn't work)
if (curHeight <= minHeight - 300) {
document.getElementById('copyrights').innerHTML = "Good bye";
}
}
});
});
关于javascript - 离开底部后 300px 做一些事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38603531/