Scroll to a specific div

2019-02-24 03:24发布

I have few divs .posts which have a attr data-id which corresponds to the mysql DB id.

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

Now if I want to scroll to a specific div which I am only known to the data-id. How will I scroll to it?. My JSFiddle is here. Can anyone give an example along with a JSFiddle?

4条回答
We Are One
2楼-- · 2019-02-24 04:09

I think this would help $(".element").attr("any-attribute-of-ur-elem"); In your case it would look like: $(".post").attr("data-id") And you can scrollTo that posts. try this:

    $(document).ready(function (){
        $("#button").click(function (){
            $('html, body').animate({
               scrollTop: $(".post[data-id="+yourID+"]").offset().top
            }, 2000);
        });
    });
查看更多
老娘就宠你
3楼-- · 2019-02-24 04:17

You don't need javascript if you have an anchor with a name.

<a href="#post8">Div to post 8</a> scrolls to <a name="post8"></a>

查看更多
姐就是有狂的资本
4楼-- · 2019-02-24 04:23

You use link anchors and JQuery. Just give your link the class "scroll" and use the following code in the head:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event) {
    event.preventDefault();
    $('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
    } );
  } );

You also need to give your posts an ID and link to them as in:

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

JSFIDDLE

查看更多
走好不送
5楼-- · 2019-02-24 04:31

You can use jQuery.ScrollTo plugin: https://github.com/flesler/jquery.scrollTo

In this link you can find demos 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>
查看更多
登录 后发表回答