Scroll to a specific div

前端 未结 5 716
猫巷女王i
猫巷女王i 2021-01-19 00:44

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

相关标签:
5条回答
  • 2021-01-19 00:57

    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>

    0 讨论(0)
  • 2021-01-19 00:58

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

    0 讨论(0)
  • 2021-01-19 01:00

    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);
            });
        });
    
    0 讨论(0)
  • 2021-01-19 01:03

    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>

    0 讨论(0)
  • 2021-01-19 01:08

    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>
    
    0 讨论(0)
提交回复
热议问题