滚动到达元素时如何执行函数?

时间:2018-02-12 12:22:51

标签: javascript jquery html css css3

我想隐藏所有元素,但是第一个元素,所以我使用$(".item:not(:eq(0))").fadeOut();

我有相同类别的元素" item":

<div class="item">First Item</div>
<div class="item">Second Item</div>
<div class="item">Third Item</div>
<div class="item">Fourth Item</div>

然后当我滚动到下一个可能是&#34;第二个,第三个,第四个项目&#34; ,我想展示它

我尝试使用:

    function isScrolledIntoView(elem)
{

 var centerY = Math.max(0,((jQuery(window).height()- 
                  jQuery(elem).outerHeight()) / 2) 
                  + jQuery(window).scrollTop());

    var elementTop = jQuery(elem).offset().top;
    var elementBottom = elementTop + jQuery(elem).height();

    return elementTop <= centerY && elementBottom >= centerY;
    }


    jQuery(window).on("scroll resize", function() {
        jQuery(".news:not(:eq(0))").each(function(index, element) {
            if (isScrolledIntoView(element)) {
               jQuery(element).fadeIn(10000);
            }
        });
    });

但它不适用于我的方法,因为身体的高度会在显示下一个项目时发生变化&#34;第二项&#34; ,所以当我滚动到&#34;第二项&#34;时,会显示所有项目。或任何其他项目。

如何隐藏第一个项目然后fadIn()每个项目滚动到它?

2 个答案:

答案 0 :(得分:0)

  

这是在jquery中使用offset()。该演示将触发函数if   您的元素完全位于视口中。

提示:您需要注意元素的内部和外部高度。

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
body{
height:200vh;
}
#test {
  top: 100vh;
  padding: 10px;
  width: 300px;
  position: relative;
  border: 1px solid black;
  height:100;
}
</style>
</head>
<body>
<p>scroll to test</p>

<div id="test">
  <p>Click the button to get offsetTop for the test div.</p>
</div>


<script>
$(document).ready(function(){
    $(window).scroll(function(){
        var x = $("#test").offset();
        var height1 = $("#test").outerHeight();
        var y = document.documentElement.scrollTop;
        var z = (x.top + height1) - y;
        if(z < $(window).height()){
             alert("fumction");
        }
    });
});
</script>

</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用waypoint.js和animate.css的组合会更容易。 将动画类添加到要动画的每个元素。您可以使用任何animate.css效果。 更改偏移量{offset:'80%'}以控制动画何时开始。

<div class="animated waypoint-slideup">

</div>

$('.waypoint-slideup').waypoint(function () {
    $(this).addClass('slideInUp');
}, { offset: '80%' });

在css文件中使用它

.waypoint-slideup{
opacity:0;}
.waypoint-slideup.slideInUp{
opacity:1;}