简体   繁体   中英

Bootstrap Navbar not collapsing with Smooth Scroll Script

I'm using the Bootstrap Navbar on a one-page website and each anchor is linked to a section on the page. I'm using a very simple javascript to smooth scroll to each section, however this somehow conflicts the collapse function of the navbar - when I click on a link it doesn't collapse anymore which is annoying. I first thought it might be a HTML problem (solved here: Bootstrap Navbar Collapse not closing on Click ) but figured out it is a JS problem - any ideas?

HTML:

<nav class="navbar navbar-default mainbar" role="navigation">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle hvr-bounce-to-bottom collapsed" data-toggle="collapse" data-target="#my-navbar-collapse">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
    </div>

    <div class="collapse navbar-collapse" id="my-navbar-collapse">
      <ul class="nav navbar-nav">
         <li><a data-toggle="collapse" data-target=".navbar-collapse" href="#link1" class="navelement">Link 1</a></li>

         <li><a data-toggle="collapse" data-target=".navbar-collapse" href="#link2" class="navelement">Link 2</a></li>

       </ul>
     </div>
</nav>

JAVASCRIPT:

var corp = $("html, body");
  $(".navelement").click(function() {
    var flag = $.attr(this, "href");
    corp.animate({
        scrollTop: $(schild).offset().top - 60
    }, 1600, function() {
        window.location.hash = flag;
    });
    return false;
});

you can use jQuery :not selector-utility

eg

$('a[href*=#]:not([href=#], [data-toggle=collapse])').click(function(){...})

or in your example:

var corp = $("html, body");
  $(".navelement:not([data-toggle=collapse])").click(function() {
    var flag = $.attr(this, "href");
    corp.animate({
        scrollTop: $(schild).offset().top - 60
    }, 1600, function() {
        window.location.hash = flag;
    });
    return false;
});

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