Scroll to element using data-attributes

谁都会走 提交于 2021-01-28 04:57:05

问题


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.net/clestcruz/vf4ufg6b/


回答1:


Concatenate 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



来源:https://stackoverflow.com/questions/36471679/scroll-to-element-using-data-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!