javascript - JQuery平滑滚动到带有粘性导航栏的锚点
问题描述
我有一个带有粘性标题的网页,我正在尝试实现平滑滚动到锚标记以进行导航。当我单击指向我想去的部分的导航链接时,scrollTop: href.offset().top - 100
似乎无法正常工作。如果我在网页导航到该部分后再次单击该链接,我可以看到页面滚动,但随后它会弹回顶部。知道发生了什么吗?我正在使用 Microsoft Edge(是的,我知道......)。
HTML
<!DOCTYPE HTML>
<html lang="en">
<head></head>
<body id="home">
<nav><a href="#section1">Section #1</a></nav>
<main>
<!-- INSERT A BUNCH OF <BR> TAGS -->
<h2 id="section1">section1</h2>
<!-- INSERT A BUNCH OF <BR> TAGS -->
</main>
</body>
</html>
CSS
nav {
position:fixed;
padding:4px;
border:2px solid #000;
width:100%;
line-height:2.25em;
background-color:yellow;
}
h2 {
padding:4px;
border:1px solid #000;
width:100%;
line-height:100px;
background-color:red;
}
jQuery
$(document).ready(function() {
$('a[href*="#"]').click(function(event) {
var href = $(this.hash);
if (href.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: href.offset().top - 100
}, 750, function() {
location.hash = href.attr('id');
});
}
});
});
编辑:
我了解将<div>
元素设置为display:fixed
将其从页面流中删除,我认为这是导致问题的原因。有解决办法吗?
解决方案
编辑:
Edge 和 Firefox 不配合初始方法来修改hashchange
行为,因此此编辑只是删除了window.location.hash
防止动画后跳转的步骤。但是,这并不理想,因为它会阻止默认的哈希位置行为。
$(document).ready(function() {
$('a[href*="#"]').on('click', (event) => {
const hash = event.currentTarget.hash;
if (hash) {
event.preventDefault();
$('html, body').animate({scrollTop: $(hash).offset().top - 100}, 750);
}
});
});
nav {
position: fixed;
padding: 4px;
border: 2px solid #000;
width: 100%;
line-height: 2.25em;
background-color: yellow;
}
h2 {
padding: 4px;
border: 1px solid #000;
width: 100%;
line-height: 100px;
background-color: red;
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body id="home">
<!-- Navigation -->
<nav><a href="#section1">Section #1</a></nav>
<!-- Main Content -->
<main>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<h2 id="section1">section1</h2>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
</main>
</body>
</html>
原来的:
我认为动画完成location.hash
后会导致滚动跳到顶部。scrollTop
您可以修改hashchange
事件以在锚点上方相同距离处停止滚动以消除跳跃。
$(document).ready(function() {
$(window).on('hashchange', function() {
window.scrollTo(window.scrollX, window.scrollY - 100);
});
$('a[href*="#"]').on('click', (event) => {
const hash = event.currentTarget.hash;
if (hash) {
event.preventDefault();
$('html, body').animate({
scrollTop: $(hash).offset().top - 100
}, 750, function() {
window.location.hash = hash;
});
}
});
});
推荐阅读
- coq - 用暗示代替假设而不添加其前提作为子目标
- c - 在第二条对角线下打印矩阵和数字
- node.js - 可以以某种方式减少/解决这些 npm 警告吗?
- angular - 如何在 ngx-bootstrap/datepicker 中设置选定的日期,该日期是在将图标单击到常见的 html 输入时启动的?
- swift - 引用实例方法需要等效性 (SWIFT)
- text - 用视觉模式选择多个文本点?
- reactjs - 如何使用 onClick 获取 props 并在 redux 中使用组件传递?
- reactjs - React 从 useEffect 中的 Redux 商店获取状态
- python - 如何使用散景创建比例(预定义边界)彩条?
- node.js - 使用 google api 库编译打字稿时出现“错误 TS2304:找不到名称‘Long’”