简体   繁体   中英

How do you implement smooth scrolling with a fixed sidebar in Bootstrap?

Trying to implement smooth scroll doesn't seem to be working. Is it because of the sidebar nav?

I'm still somewhat new to JQuery and JS in general. I'm setting up a new site in Bootstrap 4 using a sidebar nav, and want to implement smooth scroll to the nav links/anchor tags in my HTML. I've set up smooth scroll on other sites before but it doesn't seem to be working for me this time and I can't figure out what's going on!

My HTML:

<nav id="sidebar">
        <div class="sidebar-header text-center">
            <h3>DS</h3>
        </div>
        <ul class="list-unstyled components">
            <li class="active">
                <a href="#home" class="smooth-scroll">Home</a>
            </li>
            <li>
                <a href="#about" class="smooth-scroll">About</a>
            </li>
        </ul>

        <ul class="list-unstyled CTAs">
            <li>
                <a href="#" class="download">Download Resume PDF</a>
            </li>
        </ul>
    </nav>
<div class="blank-section" id="about"></div>
<div class="regular-padding">
    <h3 id="about-h3"><mark>About Me</mark></h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse efficitur dapibus dolor eget finibus. Donec vulputate ultrices mauris eget hendrerit. Integer viverra dui ipsum, id egestas ex laoreet viverra. Proin elit ipsum, sagittis sed ullamcorper at, viverra nec lacus. Proin magna sem, lacinia vitae varius ut, sollicitudin efficitur tellus. Integer vel vulputate purus. Duis quis elit laoreet, condimentum ipsum eget, venenatis felis.</p>
</div>
</div>`

My JS:

// sidebar collapse
$(document).ready(function () {
  $('#sidebarCollapse').on('click', function () {
    $('#sidebar, #content').toggleClass('active');
    $('.collapse.in').toggleClass('in');
    $('a[aria-expanded=true]').attr('aria-expanded', 'false');
  });
});

//smooth scroll
$(document).ready(function() {
  $('#sidebar ul li a').click(function(e) {
 var targetHref = $(this).attr('href');
$('html, body').animate({
    scrollTop: $(targetHref).offset().top
}, 1000);
e.preventDefault();
  });
});

The anchor tags are working correctly and the sidebar is collapsing/expanding as it should, but smooth scroll still isn't executing.

You should start your function with e.preventDefault() , that's how you keep the browser from scrolling and instead you are using jQuery's animate function to execute the scroll. In your case the browser does it's thing before jQuery and your scroll effect is invisible because the user is already at the target destination.

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