How to scroll to div after click on About or Contact in my menu?

前端 未结 3 800
说谎
说谎 2021-02-06 13:43

How to scroll to div (e.g: #about, #contact) after click on About or Contact in my menu?

相关标签:
3条回答
  • 2021-02-06 14:23

    Your html:

    <div class="masthead">
        <ul class="nav nav-pills pull-right">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
        </ul>
        <h3 class="muted">Name site</h3>
    </div>
    <div id="about">about</div>
    <div id="contact">contact</div>
    

    Your javascript:

    $('ul.nav').find('a').click(function(){
        var $href = $(this).attr('href');
        var $anchor = $('#'+$href).offset();
        window.scrollTo($anchor.left,$anchor.top);
        return false;
    });
    

    If you want to use animate, replace

    window.scrollTo($anchor.left,$anchor.top);
    

    by

    $('body').animate({ scrollTop: $anchor.top });
    
    0 讨论(0)
  • 2021-02-06 14:31

    It is easier than you think.

      <div class="masthead">
        <ul class="nav nav-pills pull-right">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#About">About</a></li>
          <li><a href="#Contact">Contact</a></li>
        </ul>
        <h3 class="muted">Name site</h3>
      </div>
    
    
    <div id="About">Here's my about</div>
    
    ...
    
    <div id="Contact">Here's my contact</div>
    

    By using the hash, it'll auto scroll to an element with that id (or an anchor with that name attribute). If you want it to scroll smoothly you can enhance the scroll effect with a javascript library, like jquery. See this question: How to scroll HTML page to given anchor using jQuery or Javascript?

    0 讨论(0)
  • 2021-02-06 14:33

    You can jump to it with HTML via:

    <a href="#tips">Visit the Useful Tips Section</a> 
    

    You can do it with CSS via:

    http://css-tricks.com/snippets/jquery/smooth-scrolling/

    0 讨论(0)
提交回复
热议问题