当滚动到顶部而不是底部时添加元素

Add element when scroll to top instead of bottom

本文关键字:底部 添加 元素 滚动 顶部      更新时间:2023-09-26

这一定是一些愚蠢的错误,但在我的javascript函数中,当我到达屏幕底部时应该执行的if语句,当我达到屏幕顶部时正在执行。。。这是我的代码:

$(window).scroll(function() {       //detect page scroll        
    if($(window).scrollTop() + $(window).height() == $(document).height())  //user scrolled to bottom of the page?
         {
         $('.animation_image').show(); //show loading image
         }
});

.animation_image是一个加载图像,当我到达屏幕底部时会出现,但当我向下滚动然后返回屏幕顶部时会出现。。。

如果有人能解释我做错了什么,那就太好了!

它应该能正常工作。尽管只是出于好奇,但此代码从未隐藏图像。难道它不应该在其他地方藏起来吗?给你,Fiddlehttps://jsfiddle.net/3eg18L8u/

$(window).scroll(function() {       //detect page scroll        
if($(window).scrollTop() + $(window).height() == $(document).height())  //user scrolled to bottom of the page?
     {
     $('.animation_image').show(); //show loading image
     }
else {
     $('.animation_image').hide(); //show loading image
}

});

您尝试过>=而不是==吗?

if ($(window).scrollTop() + $(window).height() >= $(document).height())     
{
     $('.animation_image').show(); //show loading image
}

怎么样:

$(document).ready(function(){
    $(window).scroll(function(e){
        e.stopPropagation();
        e.preventDefault();
        var scrollBottom = $(document).height() - $(window).scrollTop() - $(window).height();
        if (scrollBottom == 0) {
            $('.animation-image').show();
        }
    });
});

我似乎不明白为什么即使有你们的帮助,它也不起作用,所以我放弃了,决定使用这个代码,它不是解决方案,而是一个替代方案:

function yHandler(){
var wrap = document.getElementById('wrap');
var contentHeight = wrap.offsetHeight;
var yOffset = window.pageYOffset; 
var y = yOffset + window.innerHeight;
if(y >= contentHeight){
    $('.animation_image').show();
 }
    var status = document.getElementById('status');
    status.innerHTML = contentHeight+" | "+y;
}window.onscroll = yHandler

html内容结构如下:

<body>    
<div id="status">0 | 0</div>
<div id="wrap">
*ALL CONTENT*
</div>
</body>

和CSS:

div#status{position:fixed; font-size:24px;}