简体   繁体   English

如何创建一个返回页面顶部的按钮?

[英]How to create a button to go back to the top of the page?

I created a button with a link to go back to the top of the page.我创建了一个带有返回页面顶部链接的按钮。

Here is the JS code :这是JS代码:

(function ($) {

/*--Scroll Back to Top Button Show--*/

$(window).scroll(function(){
    if ($(this).scrollTop() > 100) {
        $('#back-to-top').fadeIn();
    } else {
        $('#back-to-top').fadeOut();
    }
});

//Click event scroll to top button jquery

$('#back-to-top').click(function(){
    $('html, body').animate({scrollTop : 0},600);
    return false;
});

})(jQuery);

Here is the HTML code:这是 HTML 代码:

<a id="back-to-top" href="#">
  <i class="fas fa-chevron-circle-up fa-4x"></i>
</a>

It works very well, but I want to create a button instead of a link.它工作得很好,但我想创建一个按钮而不是链接。

I tested the following HTML code but it does not work.我测试了以下 HTML 代码,但它不起作用。 There is the button but it does not go back up the page :有按钮,但它不会返回页面:

<button type="button" id="back-to-top" href="#">
  <i class="fas fa-chevron-circle-up fa-4x"></i>
</button>

How to create a button to go back to the top of the page ?如何创建一个返回页面顶部的按钮?

It is same code for both.两者的代码相同。 But notice if you didn't remove tag, than could happend that you have duplicate id and button will not work但是请注意,如果您没有删除标签,则可能会发生重复的 id 并且按钮将不起作用

 (function ($) { /*--Scroll Back to Top Button Show--*/ $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $('#back-to-top').fadeIn(); } else { $('#back-to-top').fadeOut(); } }); //Click event scroll to top button jquery $('#back-to-top').click(function(){ $('html, body').animate({scrollTop : 0},600); return false; }); })(jQuery);
 body { min-height: 1000px; } button{ position: fixed; right: 5px; bottom: 10px; } a{ position: fixed; left: 5px; bottom: 10px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="back-to-top" type="button"> Button </button>

The javascript to take you to the top of a page is...带你到页面顶部的 javascript 是......

window.scrollTo(0,0)

So when incorporated as a link, it will look like this...所以当作为链接合并时,它看起来像这样......

<a href="javascript:window.scrollTo(0,0);">Go to top</a>

Or as a button, it will look like this...或者作为一个按钮,它看起来像这样......

<button onclick="window.scrollTo(0,0);">Go to top</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM