简体   繁体   中英

Scroll to section with jquery

So i made a navigation bar which i want to scroll to a specific section when clicked. Here is a fragment of the html code for my navigation and four sections, with the Javascript code(jquery). The problem is that it always scrolls to the top of my site and not to the specific sections. All sections have a declared height and position set to relative.

<nav class="menu">
        <ul>
            <a href="#" class="start">
                <li>Start</li>
            </a>
            <a href="#" class="about">
                <li>About</li>
            </a>
            <a href="#" class="products">
                <li>Products</li>
            </a>
            <a href="#" class="contact">
                <li>Contact</li>
            </a>
        </ul>
    </nav>
<header class="welcome" data-section="start">
<main class="about" data-section="about">
<section class="products" data-section="products">
<div class="kontakt" data-section="contact">

<script>
$('nav ul a').on('click',function(){
    const goToSection = "[data-section=" + $(this).attr('class') + "]";
    $('html body').animate({scrollTop: $(goToSection).offset.top})
})<script>

  • Its .offset().top not .offset.top
  • It will be much easier and better to add data-class attribute to the anchor so you can use $(this).data('class').trim() instead of $(this).attr('class') ( trim() to avoid any white-spaces)
  • Comma needed in $('html body') to be $('html, body')

 $(document).ready(function(){ $('nav ul a').on('click',function(){ const goToSection = "[data-section=" + $(this).data('class').trim() + "]"; $('html, body').animate({scrollTop: $(goToSection).offset().top}) }); });
 .menu{ position: fixed; background: red; color: #fff; }.menu a{ color: #fff; } header, main, section{ background: yellow; height: 500px; margin: 20px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav class="menu"> <ul> <a href="#" class="start" data-class="start"> <li>Start</li> </a> <a href="#" class="about" data-class="about"> <li>About</li> </a> <a href="#" class="products" data-class="products"> <li>Products</li> </a> <a href="#" class="contact" data-class="contact"> <li>Contact</li> </a> </ul> </nav> <header class="welcome" data-section="start">Welcome</header> <main class="about" data-section="about">About</main> <section class="products" data-section="products">Products</section> <div class="kontakt" data-section="contact">Contact</div>

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