Bootstrap4.平滑滚动可在.nav-link上进行,但不能在其他锚点上进行 [英] Bootstrap 4. Smooth scrolling working on .nav-link but not on other anchor elements

查看:98
本文介绍了Bootstrap4.平滑滚动可在.nav-link上进行,但不能在其他锚点上进行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Bootstrap 4,并且正在使用以下jQuery,以允许从.nav链接平滑滚动到部分ID(在同一页面中):

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):

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

这对于.nav-link项目非常有用,但是如果我尝试添加其他类,则代码对它们无效.例如,我添加.navbar-brand和.new-button:

This works great for .nav-link items, but if I try to add other classes, the code does not work on them. eg, I add .navbar-brand and .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.

推荐答案

它在Bootstrap 4上正常工作,并且此代码也正常工作,可能与您的其他代码有误.

Its working fine with bootstrap 4 and this code also working fine may be something wrong in your other code.

$('.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>

这篇关于Bootstrap4.平滑滚动可在.nav-link上进行,但不能在其他锚点上进行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆