【发布时间】:2023-03-24 15:43:01
【问题描述】:
我正在尝试创建滚动菜单的本地锚点。我正在使用链接在锚点和 javascript 之间滚动锚点(我知道我可以在 html 中做到这一点,但我似乎无法让它工作)。
一旦我在菜单中添加一个锚链接,它就可以正常工作,但如果我再次单击它,它会向后滚动到起点,我不明白为什么。
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top - 100
}, 500);
return false;
});
html {
overflow-x: hidden;
overflow-y: scroll;
scroll-behavior: smooth;
}
html, body {
box-sizing: border-box;
font-family: 'Varela Round', sans-serif;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow-x: hidden;
}
*,
*::before,
*::after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
::-webkit-scrollbar {
width: 0px;
background: transparent;
}
img {
width: 100%;
}
body {
background-color: #e3e3e3;
}
a{
text-decoration: none;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="position: fixed;">
<nav class="top-nav">
<ul style="direction: rtl;">
<li><a href="#service" style="cursor: pointer;">test</a></li>
<li><a href="#gallery" style="cursor: pointer;">test1</a></li>
<li><a href="#contact">test2</a></li>
</ul>
<a href="#!" id="burger-menu" onclick="toggleSideMenu()"><i class="fas fa-bars" style="color: white; font-size: 22px;"></i></a>
</div>
</nav>
</div>
<div style="margin-top: 700px;"></div>
<div id="service">
Anchor 1
</div>
<div style="margin-top: 700px;"></div>
<div id="gallery">
Anchor 2
</div>
<div style="margin-top: 700px;"></div>
<div id="contact">
Anchor 3
</div>
我确实认为问题与 body 和 html 滚动属性有关,但我坚持以这种方式保留代码,因为它与我的代码的另一部分有关。
Demo - 如果您单击其中一个子菜单两次,您将看到问题。
如何固定锚链接位置并保持其平滑滚动?
【问题讨论】:
-
我发现很难看出你想要做什么,而且似乎无法让演示工作。不管你有没有看过 affix getbootstrap.com/docs/3.3/javascript/#affix 这似乎接近你想要实现的目标
-
@RichardHousham codepen.io/yotking789/pen/zYvwgqv
-
新鲜的外观,我打赌所有这些margin-top:700px;正在推倒内容,可能会弄乱 scrollTop 不太清楚。
-
@RichardHousham 我实际上已经用 margin-top 解决了这个问题来固定 div id 的位置,但是滚动仍然使这些跳跃向后..