admin管理员组文章数量:1316336
I'm trying to figure out how I can have the element scroll to a particular element using data-attributes if it matches the ID instead of using anchor tags. Here is what I'm working.
Once the user clicks on a button it will show the content and also scroll to that particular element that matches the data-attributes. I can't seem to make it scroll
<div class="container">
<div class="post" data-id="content-one">
post one
</div>
<div class="post" data-id="content-two">
post two
</div>
</div>
<div class="container-two">
<div id="content-one" class="post-content" >
content one
</div>
<div id="content-two" class="post-content" >
content two
</div>
</div>
$(".container .post").on('click', function() {
var data_id = $(this).data('id');
$('.post-content').each(function() {
var el = $(this);
if (el.attr('id') == data_id)
el.show();
else
el.hide();
});
$('html, body').animate({
scrollTop: $(data_id).offset.top()
}, 'slow');
});
/
I'm trying to figure out how I can have the element scroll to a particular element using data-attributes if it matches the ID instead of using anchor tags. Here is what I'm working.
Once the user clicks on a button it will show the content and also scroll to that particular element that matches the data-attributes. I can't seem to make it scroll
<div class="container">
<div class="post" data-id="content-one">
post one
</div>
<div class="post" data-id="content-two">
post two
</div>
</div>
<div class="container-two">
<div id="content-one" class="post-content" >
content one
</div>
<div id="content-two" class="post-content" >
content two
</div>
</div>
$(".container .post").on('click', function() {
var data_id = $(this).data('id');
$('.post-content').each(function() {
var el = $(this);
if (el.attr('id') == data_id)
el.show();
else
el.hide();
});
$('html, body').animate({
scrollTop: $(data_id).offset.top()
}, 'slow');
});
https://jsfiddle/clestcruz/vf4ufg6b/
Share Improve this question edited Apr 7, 2016 at 9:23 rrk 15.9k4 gold badges30 silver badges47 bronze badges asked Apr 7, 2016 at 9:15 clestcruzclestcruz 1,1113 gold badges34 silver badges80 bronze badges1 Answer
Reset to default 7Concatenate a #
to the id to make a proper selector. Also the use .offset().top
because offset()
is a function which returns an object which contains current position of the element. Then we can access it using the top
key.
$('html, body').animate({
scrollTop: $( '#' + data_id).offset().top
}, 'slow');
DEMO
本文标签: javascriptScroll to element using dataattributesStack Overflow
版权声明:本文标题:javascript - Scroll to element using data-attributes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741986469a2408709.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论