我的div
.posts
data-id
个 attr mysql DB id
对应<div class="posts" data-id="1"></div>
<div class="posts" data-id="2"></div>
。
div
现在,如果我想滚动到我data-id
只知道的特定{{1}}。
我将如何滚动到它?
我的JSFiddle is here。
任何人都可以和JSFiddle一起举个例子吗?
答案 0 :(得分:9)
您使用链接锚点和JQuery。 只需为链接提供“滚动”类,并在头部使用以下代码:
jQuery(document).ready(function($) {
$(".scroll").click(function(event) {
event.preventDefault();
$('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
} );
} );
您还需要为帖子提供ID并链接到它们,如下所示:
<a href="#8" class="scroll">Go To Div 8</a>
<div class="post" id="8">
答案 1 :(得分:1)
您可以使用jQuery.ScrollTo插件:https://github.com/flesler/jquery.scrollTo
在此链接中,您可以找到演示http://demos.flesler.com/jquery/scrollTo/
$(function() {
$('body').scrollTo($('div[data-id=1]'), 1000); //scroll to div 1
});
HTML:
<div class="posts" data-id="1"></div>
答案 2 :(得分:0)
如果你有name
的锚,则不需要javascript。
<a href="#post8">Div to post 8</a>
滚动到<a name="post8"></a>
答案 3 :(得分:0)
我在这里看到很多jQuery和Javascript,简单的CSS可以为您提供帮助!
html,body {
scroll-behavior: smooth;
}
要执行此操作,请使用链接,并为其提供一个href,其中包含要滚动到的元素的ID:
<a href="sectionOne">Section One</a>
<div id="sectionOne">
<h2>Section One</h2>
</div>
但是,并不是所有的浏览器都支持scroll-behavior
属性,在这种情况下,我建议您选择顶部附近的选定答案;)
答案 4 :(得分:-1)
我认为这会有所帮助$(".element").attr("any-attribute-of-ur-elem");
在您的情况下,它看起来像:$(".post").attr("data-id")
你可以滚动到那些帖子。
试试这个:
$(document).ready(function (){
$("#button").click(function (){
$('html, body').animate({
scrollTop: $(".post[data-id="+yourID+"]").offset().top
}, 2000);
});
});