如何使用JavaScript滚动到页面顶部?滚动条立即跳到页面顶部也是可取的,因为我不希望实现平滑滚动。
当前回答
当顶部滚动条顶部小于限制底部,且底部到顶部滚动条标题为粘滞时。下面参见Fiddle示例。
var lastScroll = 0;
$(document).ready(function($) {
$(window).scroll(function(){
setTimeout(function() {
var scroll = $(window).scrollTop();
if (scroll > lastScroll) {
$("header").removeClass("menu-sticky");
}
if (scroll == 0) {
$("header").removeClass("menu-sticky");
}
else if (scroll < lastScroll - 5) {
$("header").addClass("menu-sticky");
}
lastScroll = scroll;
},0);
});
});
https://jsfiddle.net/memdumusaib/d52xcLm3/
其他回答
旧的#top可以做到这一点
document.location.href = "#top";
适用于FF、IE和Chrome
<script>
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
</script>
html格式
<a href="#top">go top</a>
您可以使用javascript的内置函数scrollTo:
函数滚动(){window.scrollTo({顶部:0,行为:“平滑”});}<button onclick=“scroll”>滚动</button>
最短的
location='#'
这种解决方案是对pollinrata答案的改进,并且有一些缺点:没有平滑的滚动和更改页面位置,但最短
如果您想滚动到具有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;
});
});``