jQuery动画滚动到位置不起作用

时间:2017-07-27 04:27:21

标签: jquery css

我使用了this Stack Overflow answer中的一些代码,但我似乎无法让它因某些原因而运行。

当页面滚动到此元素时,我希望此元素将不透明度从0更改为1,但无论出于何种原因,它似乎都不起作用。该元素可能是从页面顶部向下2000px。



$(document).ready(function() {

    /* Every time the window is scrolled ... */
    $(window).scroll( function(){

    /* Check the location of each desired element */
    $('.animate').each( function(i){

        var bottom_of_object = $(this).offset().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();

        /* If the object is completely visible in the window, fade it in */
        if( bottom_of_window > bottom_of_object ){

            $(this).animate({'opacity':'1'},500);

        };

    }); 

});

});

body {
  height: 2200px;
}
#circle {
      background: #bf1e2c;
      width: 300px;
      height: 300px;
      border-radius: 100%;
      position: absolute;
      top: 25px;
    }

    .animate{
        opacity:0;
    }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="circle" class="animate"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您错过了文档就绪包装的结束}); ...

$(document).ready(function() {

    /* Every time the window is scrolled ... */
    $(window).scroll( function(){

        /* Check the location of each desired element */
        $('.animate').each( function(i){

            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();

            /* If the object is completely visible in the window, fade it in */
            if( bottom_of_window > bottom_of_object ){

                $(this).animate({'opacity':'1'},500);

            }

        }); 

    });
});

您需要滚动到该项目才能显示它。

示例小提琴不起作用:https://jsfiddle.net/bcom16pt/

示例小提琴工作:https://jsfiddle.net/bcom16pt/1/

答案 1 :(得分:0)

这是因为我在html和正文上设置了overflow-x: hidden

html,body{
    width: 100%;
    height: 100%;
    margin: 0px;
    padding: 0px;
    overflow-x: hidden;
}

当我发表评论overflow-x: hidden;时,它会有效。