首页 > 解决方案 > 如何创建一个返回页面顶部的按钮?

问题描述

我创建了一个带有返回页面顶部链接的按钮。

这是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);

这是HTML代码:

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

它工作得很好,但我想创建一个按钮而不是链接。

我测试了以下 HTML 代码,但它不起作用。有按钮,但它不返回页面:

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

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

标签: javascriptjquerycssbuttonscroll

解决方案


两者的代码相同。但是请注意,如果您没有删除标签,那么您可能会出现重复的 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>


推荐阅读