Javascript 单击按钮时如何滚动到顶部?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10461152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to scroll to top when a button is clicked?
提问by Ronny Kibet
I have a button on a page and I want that when it is clicked, the page scrolls to the 0 position.
我在页面上有一个按钮,我希望当它被点击时,页面会滚动到 0 位置。
HTML
HTML
<button id="button">Back to top </button>
jquery
查询
$(document).scroll(function(){
var scroll_pos = $(window).scrollTop()
if(scroll_pos > 10){
$('#button').click(function(){
// what code to enter here??
});
}
});
回答by VisioN
Try this code:
试试这个代码:
$("#button").on("click", function() {
$("body").scrollTop(0);
});
Method on
binds a click
event to the button and scrollTop
scrolls your body
to 0 position.
方法on
将click
事件绑定到按钮并将scrollTop
您滚动body
到 0 位置。
回答by Selvamani
you can use window function for scrollTop
jquery
您可以将窗口函数用于scrollTop
jquery
$("#button").click( function() {
$(window).scrollTop(0);
});
When you click button, this page scroll to top of the position.
当您单击按钮时,此页面会滚动到该位置的顶部。
回答by NIDHINgL
Try It
尝试一下
$("#button").click(function() {
$("html").scrollTop(0);
});
or
或者
$("#button").click(function() {
$("html").animate({ scrollTop: 0 }, "slow");
});