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 badges
Add a ment  | 

1 Answer 1

Reset to default 7

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

本文标签: javascriptScroll to element using dataattributesStack Overflow