简体   繁体   中英

Scroll to a specific div

I have few div s .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?

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

 $(function() { // Listen for a click event on the anchor $('.scroll').click(function(event) { // Prevent the jump to target that is default browser behavior event.preventDefault(); // Animate the scrollTop property of the scrollParent to the top offset // of the target element. In this case, we have an animation duration of 1000ms(1 second). $('html').animate({ scrollTop: $(this.hash).offset().top }, 1000); }); });
 /* Just for demo purposes */ .post { margin: 100vh 0; background: yellow; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="#anchor" class="scroll">Go To Div 8</a> <div class="post" id="anchor">Scroll to me</div>

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>

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>

I'm seeing a lot of jQuery and Javascript in here, and simple CSS is here to help!

html,body {
    scroll-behavior: smooth;
}

To put this in action, use a link and give it an href with the id of the element you're scrolling to:

<a href="sectionOne">Section One</a>

<div id="sectionOne">
    <h2>Section One</h2>
</div>

Not all browsers however support the scroll-behavior property, in which case I'd recommend the selected answer near the top ;)

Animate to last item with specific attribute

$('html').animate({
   scrollTop: $('className:last[data-id]').offset().top - 100
}, 500);

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);
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM