2017-07-27 70 views
-1

我使用this Stack Overflow answer一些代码,但我似乎无法得到它的工作原因。jQuery动画滚动到位置不工作

当页面滚动到此元素时,我希望此元素将不透明度从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>

回答

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/

+0

啊,该死的,忘了粘贴在这个问题。只是修复它。 – rpivovar

0

这是因为我对HTML和身体overflow-x: hidden集。

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

它在我注释掉overflow-x: hidden;时有效。

+0

得到了这个堆栈溢出答案:https://stackoverflow.com/a/5686933/7386637 – rpivovar