gpt4 book ai didi

javascript - 平滑滚动到 id,除非用户已经位于该位置

转载 作者:行者123 更新时间:2023-11-28 06:23:16 26 4
gpt4 key购买 nike

当用户单击按钮时,我正在运行以下脚本,以滚动到页面上的特定 div,以及其他一些不相关的功能。

问题在于,按钮本身应该始终保持在 View 中,因此可能会被垃圾点击,导致页面在忙于一遍又一遍地移动到同一位置时“滞后”。我想通过仅在页面尚未位于该特定位置时执行滚动来应对这种行为。

不幸的是,我没有使用 JavaScript/jQuery 的真正经验,并且无法找到使用类似内容的示例。

这是我的示例代码:

HTML

<div id="navButton">Button</div>

<div id="listContent">Content that must be visible after button click goes here</div>

脚本

window.onload=function(){
document.getElementById("navButton").onclick = function(){
$("html, body").animate({scrollTop: $("#listContent").offset().top -165}, 400);
}
}

最佳答案

也许这个示例可以帮助您...先更改哈希,然后监听 hashchange 事件。当您重新加载页面时,它将向下滚动到您的 anchor 。

 $(document).ready(function() {
// check for hash when page has loaded
if (getHash() != null) {
checkForScrolling();
}
});
// check for hash when hash has changed
window.onhashchange = function() {
checkForScrolling();
};
// return hash if so or null if hash is empty
function getHash() {
var hash = window.location.hash.replace('#', '');
if (hash != '') {
return hash;
} else {
return null;
}
}
// this function handles your scrolling

function checkForScrolling() {
// first get your element by attribute selector
var elem = $('[data-anchor="' + getHash() + '"]');
// cheeck if element exists
if (elem.length > 0) {
$('html, body').stop().animate({
scrollTop: elem.offset().top
}, 300);
}
}
 body {
font-family: Helvetica
}
section {
position: relative;
margin-bottom: 10px;
padding: 20px;
height: 300px;
background-color: #eee;
}
section a {
display: block;
position: absolute;
bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1 data-anchor="start">Smooth Scrolling</h1>
<ul>
<li><a href="#1">Scroll to Anchor 1</a>
</li>
<li><a href="#2">Scroll to Anchor 2</a>
</li>
<li><a href="#3">Scroll to Anchor 3</a>
</li>
</ul>
<section>
<h2 data-anchor="1">First Anchor</h2>
<a href="#start">Back to top</a>
</section>
<section>
<h2 data-anchor="2">Second Anchor</h2>
<a href="#start">Back to top</a>
</section>
<section>
<h2 data-anchor="3">Third Anchor</h2>
<a href="#start">Back to top</a>
</section>
</div>

关于javascript - 平滑滚动到 id,除非用户已经位于该位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35337894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com