gpt4 book ai didi

javascript - 滚动到特定的 div

转载 作者:搜寻专家 更新时间:2023-11-01 05:00:53 26 4
gpt4 key购买 nike

我有几个 div .posts 有一个 attr data-id 对应于 mysql 数据库 ID

<div class="posts" data-id="1"></div>
<div class="posts" data-id="2"></div>

现在,如果我想滚动到只有 data-id 知道的特定 div。我将如何滚动到它?我的JSFiddle is here .谁能举个例子和 JSFiddle?

最佳答案

您使用链接 anchor 和 JQuery。只需给您的链接类“滚动”并在头部使用以下代码:

$(function() {
// Listen for a click event on the anchor
$('.scroll').click(function(event) {

// Prevent the jump to target that is default browser behavior
event.preventDefault();

// Animate the scrollTop property of the scrollParent to the top offset
// of the target element. In this case, we have an animation duration of 1000ms(1 second).
$('html').animate({
scrollTop: $(this.hash).offset().top
}, 1000);
});
});
/* Just for demo purposes */
.post {
margin: 100vh 0;
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="#anchor" class="scroll">Go To Div 8</a>
<div class="post" id="anchor">Scroll to me</div>

关于javascript - 滚动到特定的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23786366/

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