javascript - 在 Bootstrap 4 中,Back-to-top 不再起作用
问题描述
我正在尝试使用 fontawesome 图标集在 bootstrap 4 中实现一个带有 js 的返回顶部按钮。一周前它运行良好,但自从我在网站上更改了其他一些东西后,它就停止了工作。这可能是一个简单的错误,但我是 js 新手,不知道如何解决这个问题......这是我的代码:
$(document).ready(function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 50) {
$('#back-to-top').fadeIn();
} else {
$('#back-to-top').fadeOut();
}
});
// scroll body to 0px on click
$('#back-to-top').click(function() {
$('body,html').animate({
scrollTop: 0
}, 400);
return false;
});
});
.back-to-top {
position: fixed;
bottom: 25px;
right: 25px;
display: none;
}
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height:100rem;">test</div>
<a id="back-to-top" href="#" class="mr-m2b btn btn-primary btn-lg back-to-top" role="button">TOP<i class="fas fa-chevron-up"></i></a>
它曾经完美地工作,但我以某种方式破坏了它,我不确定如何...... javascript似乎是问题,因为它几乎什么也没做,问题是为什么?为什么它以前可以工作,但现在不行,当我根本没有接触这个功能的时候?!
编辑:我最近删除了一个自定义滚动条
body::-webkit-scrollbar {
width: 1em;
}
body::-webkit-scrollbar-track {
box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}
body::-webkit-scrollbar-thumb {
background-color: #A1394F;
outline: 1px solid slategrey;
}
但是将其复制回去也无济于事。完全相同的复制粘贴的 js 代码在这里的代码片段中有效,但在我的 html 页面上无效……我错过了什么?
解决方案
它的工作示例,如果您的代码在您的项目中不起作用,请尝试此操作。
// 仅使用 body 而不是 "body, html" 或创建 id 并放入 body<body id="top">
然后将js编辑成document.querySelector('#top').scrollIntoView({ behavior: 'smooth' });
或者试试这个超级流畅的http://iamdustan.com/smoothscroll/
JS
// Go to Top
$(document).ready(function(){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 800) {
$('#back-to-top').fadeIn();
} else {
$('#back-to-top').fadeOut();
}
});
// scroll to top
document.querySelector('.back-to-top').addEventListener('click', function(e) {
e.preventDefault();
document.querySelector('body').scrollIntoView({ behavior: 'smooth' });
});
});
推荐阅读
- c++ - std::array 和 std::vector 的混合替代方案?
- authentication - SwiftUI 确定初始视图
- python - “RequestsCookieJar”对象不可调用
- ios - 请问,如何将此动画从 kotlin 更改为 swift?
- javascript - 如何在 AWS Amplify/AppSync 中为深度嵌套关系建模
- html - 将 HTML 转换为 PDF 时,在每页上重复左侧部分
- haskell - Haskell:如何为构造函数定义构造函数类Foldable的实例
- django - 有没有办法在不使用 CLI 的情况下在 Heroku 上为 Django 应用程序创建超级用户?
- objective-c - 怪癖消失的空白字符串
- python - Django 3.1.3 中的电子邮件激活链接问题