javascript - 在 jQuery 滚动条上淡入淡出 div

标签 javascript jquery html fadein

我有几个 div,它们本质上只是彩色矩形以帮助可视化。当我向下滚动页面时,每个矩形应该 fadeInfadeOut 取决于滚动条位置。不幸的是,它吓坏了,褪色更像是痉挛性频闪灯。我认为最好根据我在每个元素中滚动的距离来确定不透明度级别,但我什至不确定从哪里开始这种愚蠢行为。

似乎this guy有一个类似的问题,但答案没有用。

FIDDLE

jQuery

$(document).ready(function(){
    var $element_array = $("#content").find("div");
    $(window).scroll(function(){
        $element_array.each (function(){
            if (($(this).position().top + $(this).height()) < $(window).scrollTop())
                $(this).fadeIn();
            if (($(this).position().top + $(this).height()) > $(window).scrollTop())
                $(this).fadeOut();
        });
    });
 });

HTML

<div id="content">
    <div id="bg1"></div>
    <div id="bg2"></div>
    <div id="bg3"></div>
</div>

CSS

html,body{height:100%;margin:0;}
#content{
    background:#333333;
    height:2000px;
    z-index:1;
}
#bg1{
    background:blue;
    height:400px;
    width:100%;
    z-index:2;
    position:fixed;
    top:100px;
    display: none;
}
#bg2{
    background:green;
    height:400px;
    width:100%;
    z-index:3;
    position:fixed;
    top:200px;
    display: none;
}
#bg3{
    background:red;
    height:400px;
    width:100%;
    z-index:4;
    position:fixed;
    top:300px;
    display: none;
}

最佳答案

这里有一些问题

一个问题是 $(this).position().top 为每个 div 返回 0(由于它们的固定性质)。您需要解析实际的 css 值。

第二个是函数 fadeIn()fadeOut() 的性质。如果您在淡出的项目上调用 fadeOut(),如果在您的页面上积极滚动,它就会滞后。 但我没有在下面解决这个问题

我还将 else 放在第一个 if 之后,因为代码路径(应该)是互斥的。

$(document).ready(function(){
    var $element_array = $("#content").find("div");
    $(window).scroll(function(){
        $element_array.each (function(){
            if ((parseInt($(this).css('top')) + $(this).height()) < $(window).scrollTop())
                $(this).fadeIn();
            else if ((parseInt($(this).css('top')) + $(this).height()) > $(window).scrollTop())
                $(this).fadeOut();
        });
    });
});

关于javascript - 在 jQuery 滚动条上淡入淡出 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19258544/

相关文章:

javascript - 按名称调用 Javascript 函数

javascript - 将 click() 事件附加到 Twitter 关注按钮?

javascript - 过滤要在表中显示的行

javascript - 在 yii 中为 GridView 的点击事件创建警报按钮

javascript - Backbone.js 中的 setTimeout() 函数

jquery - 未捕获的 RangeError : Maximum call stack size exceeded in jquery autocomplete 1. 10 版本

具有范围和不同背景颜色的 jQuery slider

html - Schema.org 中网页结构的隐含性

php - 浏览器/手机检测有哪些可用的解决方案

html 密码字段 - 禁用密码管理器