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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:24:42  来源:igfitidea点击:

How to scroll to top when a button is clicked?

javascriptjquery

提问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 onbinds a clickevent to the button and scrollTopscrolls your bodyto 0 position.

方法onclick事件绑定到按钮并将scrollTop您滚动body到 0 位置。

回答by Selvamani

you can use window function for scrollTopjquery

您可以将窗口函数用于scrollTopjquery

 $("#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");
        });