简体   繁体   English

Bootstrap 4. 在 .nav-link 上平滑滚动,但不适用于其他锚元素

[英]Bootstrap 4. Smooth scrolling working on .nav-link but not on other anchor elements

I'm using Bootstrap 4, and am using the following jQuery to allow smooth scrolling from the .nav-links to section id's (within the same page):我正在使用 Bootstrap 4,并使用以下 jQuery 来允许从 .nav-links 平滑滚动到部分 ID(在同一页面内):

$('.nav-link').click(function() {
    var sectionTo = $(this).attr('href');
    $('html, body').animate({
      scrollTop: $(sectionTo).offset().top
    }, 1500);
});

This works great for .nav-link items, but if I try to add other classes, the code does not work on them.这对 .nav-link 项目很有用,但如果我尝试添加其他类,代码对它们不起作用。 eg, I add .navbar-brand and .new-button:例如,我添加 .navbar-brand 和 .new-button:

$('.nav-link, .navbar-brand, .new-button').click(function() {
    var sectionTo = $(this).attr('href');
    $('html, body').animate({
      scrollTop: $(sectionTo).offset().top
    }, 1500);
});

Any help greatly appreciated.非常感谢任何帮助。

Set scroll-behavior in css and it will do the effect.在 css 中设置滚动行为,它会产生效果。

html {
  scroll-behavior: smooth;
}

Here's a link to the example: https://jsfiddle.net/mzjan/set7aLnp/这是示例的链接: https : //jsfiddle.net/mzjan/set7aLnp/

Its working fine with bootstrap 4 and this code also working fine may be something wrong in your other code.它与 bootstrap 4 一起工作正常,并且此代码也可以正常工作,但您的其他代码可能有问题。

 $('.test, .nav-link, .navbar-brand, .new-button').click(function() { var sectionTo = $(this).attr('href'); $('html, body').animate({ scrollTop: $(sectionTo).offset().top }, 1500); });
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <a href="#one" class="test">test class</a><br> <a href="#two" class="navbar-brand">navbar-brand class</a> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <div id="one">test class</div> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <div id="two">navbar-brand class</div> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM