javascript - 如何创建一个返回页面顶部的按钮?
问题描述
我创建了一个带有返回页面顶部链接的按钮。
这是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>
如何创建一个返回页面顶部的按钮?
解决方案
两者的代码相同。但是请注意,如果您没有删除标签,那么您可能会出现重复的 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>
推荐阅读
- javascript - 属性更改后,Angular 不会重新渲染以禁用按钮
- javascript - Javascript中的PBKDF2WithHmacSHA512解密
- excel - 如何将客户支出分为低、中、高三个范围。每个范围的值应该是多少?
- android - 最后位置不调用 RecyclerView.Adapter 的 onBindViewHolder()
- android-studio - Android中的TextWatcher没有在其他edittexts中设置值
- pycharm - 如何将新编写的函数导入pychaarm中的笔记本?
- webpack - 带变量的动态导入不起作用
- c# - 卡在 UDP 响应
- asp.net - HTTP 500.19 - 内部服务器错误。没有任何配置错误
- gitlab - Gitlab:出现了一个runner系统故障