滚动到位置的jQuery动画不起作用
Posted
技术标签:
【中文标题】滚动到位置的jQuery动画不起作用【英文标题】:jQuery animate on scroll to position not working 【发布时间】:2018-01-02 15:08:36 【问题描述】:我正在使用来自this Stack Overflow answer 的一些代码,但由于某种原因我似乎无法让它工作。
当页面滚动到该元素时,我希望该元素将不透明度从 0 更改为 1,但无论出于何种原因,它似乎都不起作用。该元素可能距离页面顶部 2000 像素。
$(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>
【问题讨论】:
【参考方案1】:您的文档就绪包装器缺少结束 );
...
$(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/
【讨论】:
啊该死的,忘记在问题中粘贴这个了。刚刚修好了。【参考方案2】:这是因为我在 html 和 body 上设置了overflow-x: hidden
。
html,body
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
overflow-x: hidden;
当我注释掉 overflow-x: hidden;
时它可以工作。
【讨论】:
从这个 Stack Overflow 答案中得到答案:***.com/a/5686933/7386637以上是关于滚动到位置的jQuery动画不起作用的主要内容,如果未能解决你的问题,请参考以下文章
如何修复“Jquery 平滑滚动动画”在 Bootstrap 上不起作用