如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
平滑滚动,纯javascript:
(function smoothscroll(){
var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothscroll);
window.scrollTo (0,currentScroll - (currentScroll/5));
}
})();
其他回答
document.getElementsByTagName('html')[0].scrollIntoView({ behavior: "smooth" });
平滑动画的更好解决方案:
// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });
参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#Example
尝试此操作以在顶部滚动
<script>
$(document).ready(function(){
$(window).scrollTop(0);
});
</script>
如果您想滚动到具有ID的任何元素,请尝试以下操作:
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 700, 'swing', function () {
window.location.hash = target;
});
});``
你可以尝试在这个Fiddle中使用JShttp://jsfiddle.net/5bNmH/1/
在页脚中添加“转到顶部”按钮:
<footer>
<hr />
<p>Just some basic footer text.</p>
<!-- Go to top Button -->
<a href="#" class="go-top">Go Top</a>
</footer>