简体   繁体   English

滚动效果不起作用时多个div淡入/淡出

[英]Multiple divs fade in/ out on scroll effect not working

I have a 3 div s which are relatively positioned on the right side of my page inside an absolute parent div. 我有一个3 div ,它相对位于绝对父div内页面的右侧。 I want them fade in and out as they scroll outside of they view (parent div). 我希望它们在视图外滚动时(父div)淡入淡出。 The fade feature was working before I set my parent div s positioning. 在设置父div的位置之前,淡入淡出功能已经开始起作用。 How do I fix this? 我该如何解决? Thanks in advance for any help! 在此先感谢您的帮助!

Here is a Codepen 这是一个Codepen

<div class="container">
    <div class="row">
        <div class="col-sm-6" id="left_content">
            <img src="buffalo.png">
        </div>
        <div class="col-sm-6" id="content">
            <div class="right_content" id="box1">
                <h4>Hi. My name is Jack.</h4>
                <p>Scroll down for more info</p>
            </div>
            <div class="right_content" id="box2">
                <h4>I'm a 21 year old developer living in Buffalo, Ny.</h4>
            </div>
            <div class="right_content" id="box3">
                <h4>Hi. My name is Jack.</h4>
                <p>Scroll down for more info</p>
            </div>
        </div>
    </div>

JS: JS:

$(window).scroll(function () {
    $('[id^="box"]').each(function () {
        if (($(this).offset().top - $(window).scrollTop()) < 20) {
             $(this).stop().fadeTo(100, .5);
        } else {
             $(this).stop().fadeTo('fast', 1);
        }
    });
});

CSS: CSS:

#left_content {
     position: fixed;
}
.right_content {
     position: relative;
}
::-webkit-scrollbar { 
     display: none;
}
#content {
     width: 45%;
     height: 400px;
     overflow: scroll;
     position: absolute;
     right: 0;
}
h4, p {
     margin-left: 10%;
}
#box1 {
     top: 250px;
}
#box2 {
     top: 650px;
}
#box3 {
     top: 1050px;
     margin-bottom: 600px;
}

Your .scroll() is not on the proper area. 您的.scroll()不在正确的区域。 Because you are actually scrolling your <div id="content"> and not the window itself, so adjust your script like so: 因为您实际上滚动的是<div id="content">而不是窗口本身,所以请像这样调整脚本:

<script type="text/javascript">

    $('#content').scroll(function () {
        $('[id^="box"]').each(function () {
            if (($(this).offset().top - $(window).scrollTop()) < 20) {
                $(this).stop().fadeTo(100, 0.5);
            } else {
                $(this).stop().fadeTo('fast', 1);
            }
        });

    });

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM