滚动到顶部动画不流畅
scroll to top not animating smoothly
我的代码:
$('#scroll-image').click(function(){
$(window).animate({scrollTop: 0}, 2000);
return false;
});
当我点击#scroll-image 时,页面会向上滚动,但它会立即发生。我想让它平滑滚动。我环顾四周,其他人使用相同的代码,他们的代码运行良好。有什么想法吗?
试试这个:
$("html, body").animate({ scrollTop: "0" }, 2000);
如:
$('#scroll-image').on('click', function(){
$("html, body").animate({scrollTop: 0}, 2000);
return false;
});
.box {
height: 1000px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<a id="scroll-image" href="#">Scroll to top</a>
你制作 html
和 body
动画的原因是因为不同的浏览器响应不同的元素——通过这两种方式,它将与更多的浏览器兼容。
您想为 html 和 body 元素设置动画,而不是 window。
$('#scroll-image').click(function(){
$("html, body").animate({ scrollTop: 0 }, 2000);
return false;
});
您在使用 $(window)
时遇到错误。请改用 $("html, body")
。
$("html, body").animate({scrollTop: 0}, 2000);
这里是fiddle.
我的代码:
$('#scroll-image').click(function(){
$(window).animate({scrollTop: 0}, 2000);
return false;
});
当我点击#scroll-image 时,页面会向上滚动,但它会立即发生。我想让它平滑滚动。我环顾四周,其他人使用相同的代码,他们的代码运行良好。有什么想法吗?
试试这个:
$("html, body").animate({ scrollTop: "0" }, 2000);
如:
$('#scroll-image').on('click', function(){
$("html, body").animate({scrollTop: 0}, 2000);
return false;
});
.box {
height: 1000px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<a id="scroll-image" href="#">Scroll to top</a>
你制作 html
和 body
动画的原因是因为不同的浏览器响应不同的元素——通过这两种方式,它将与更多的浏览器兼容。
您想为 html 和 body 元素设置动画,而不是 window。
$('#scroll-image').click(function(){
$("html, body").animate({ scrollTop: 0 }, 2000);
return false;
});
您在使用 $(window)
时遇到错误。请改用 $("html, body")
。
$("html, body").animate({scrollTop: 0}, 2000);
这里是fiddle.