首页 > 解决方案 > 平滑滚动在 Bootstrap 4 中不起作用

问题描述

我一直在尝试在我的引导站点上进行平滑滚动工作。我一直在这个网站上研究不同的代码,这是我坚持的那个,但它不会动画。我不确定它是否像选择器不是正确的那样简单,或者问题可能是什么。

谢谢!

HTML

<body data-spy="scroll" data-target="#navbar">
    <nav id="navbar" class="navbar navbar-expand-lg navbar-dark sticky-top">
      <a href="index.html" id="navbarBrand" class="navbar-brand">Stages of Change Counseling</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div id="navbarNav" class="collapse navbar-collapse">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a href="#home" class="nav-link">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a href="#about" class="nav-link">About</a>
          </li>
          <li class="nav-item">
            <a href="#services" class="nav-link">Services</a>
          </li>
          <li class="nav-item">
            <a href="#approach" class="nav-link">Approach</a>
          </li>
          <li class="nav-item">
            <a href="#commitment" class="nav-link">Commitment</a>
          </li>
          <li class="nav-item">
            <a href="#contact" class="nav-link">Contact</a>
          </li>
        </ul>
      </div><!--navbarNav-->
    </nav>

    <main>
      <section id="home">
        <div class="container-fluid">
          <div class="row">
            <div class="col-12 px-0">
              <img class="img-fluid" src="img/lotus.jpg" alt="Lotus flower">
            </div><!--col-->
            <div class="col-lg-10 col-10 mx-auto">
              <p id="cta">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. .</p>
            </div>
            <div class="col-lg-6 col-10 mx-auto">
              <p class="main-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div><!--col-->
          </div><!--row-->
        </div><!--container-->
      </section>
      
      <section id="about">
        <div class="container-fluid">
          <div class="row">
            <div class="col-xl-5 offset-xl-1 col-12">
              <img src="img/portrait.jpg" alt="A portrait of myself wearing a mint sweater and a flower flower pattern scarf" class="img-fluid d-block mx-sm-auto">
            </div><!--col-->
            <div class="col-xl-4 col-10 mx-auto">
              <h1 class="header">About me</h1>
              <p class="main-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
              <br><br>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div><!--col-->
          </div><!--row-->

          <div class="row">
            <div class="col-xl-8 col-10 mx-auto">
              <p class="main-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
              <br><br>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div><!--col-->
          </div><!--row-->
        </div><!--container-->
      </section>
      
      <section id="approach">
        <div class="container-fluid">
          <div class="row">
            <div class="col-12">
              <h1 class="header">Approach</h1>
            </div><!--col-->
            <div class="col-12 px-0">
              <img src="img/staircase.jpg" alt="spiral staircase" class="img-fluid">
            </div>
            <div class="col-md-8 col-10 mx-auto">
            <p class="main-text">By listening deeply to each client before me, I strive to be fully present without preconceptions. By listening with an open heart to each person’s struggles, I pull from a lifetime of experience. Assessing which approaches may begin a particular client’s process of mitigating suffering may result in collaborating to start with a behavioral assignment, a cognitive restructuring process, dialoging with internal parts to release deeply held pain, or simply offering compassionate presence. The unique interaction between each individual and myself will yield different proscriptive approaches each time, <b>I definitely do not use a one size fits all approach.</b> Since healing often comes from a place of deep inner peace, behavioral homework may involve forms of meditation or relaxation to enhance systemic de-stressing. 
            <br><br>
            For the client’s part, awareness that change takes <b>effort</b>, is of paramount importance. Whatever a person’s configuration of functioning, it can usually only be changed, like building a wall or taking down a wall, brick by brick. That’s why my practice is called Stages of Change. Each person’s readiness to change and ability to apply focused, persistent effort unfolds at their own pace. As a wonderful teacher of mine said, “A therapist has maps but the client has to sit in the driver’s seat and put their foot on the gas.”
            <br><br>
            Albert Ellis used to have client’s put a banana on a leash and pull it down a crowded New York street to inoculate clients to what others’ thought of them! While few would relish a behavioral assignment like that, observation of the flow of one’s thoughts, courage to feel difficult feelings or journaling may help one know oneself at a deeper level. Surprising oneself with new capabilities built by taking risks can be deeply empowering. 
            </p>
            </div><!--col-->
          </div><!--row-->
        </div><!--container-->
      </section>

jQuery

$("#navbarNav .navbar-nav li .nav-link").on('click', function(smooth) {

//set hash
var target = this.hash;

//prevent default clicking behavior
smooth.preventDefault();

//grab height of the navbar
var navOffset = $('#navbar').height();

//animate the scroll
return $('html, body').animate({
  scrollTop: $(this.hash).offset().top - navOffset
}, 600, function() {
    //add hash to the end of URL
  return window.history.pushState(null, null, target);
});

});

这是codepen https://codepen.io/hailtothev612/pen/XWdOWQd

标签: jquerybootstrap-4

解决方案


此代码笔不起作用的唯一原因是因为您使用的是 jQuery 代码,但网站上未加载 jQuery。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

添加此代码后,滚动工作正常。

  1. 确保在脚本之前加载 jQuery。
  2. 确保您没有使用 jQuery Slim(功能较少的较小版本),因为它不支持 animate() 函数。

始终调试代码(浏览器和控制台选项卡中的 F12)以查找问题。

$("#navbarNav .navbar-nav li .nav-link").on('click', function(smooth) {

    //set hash
    var target = this.hash;
    
    //prevent default clicking behavior
    smooth.preventDefault();
    
    //grab height of the navbar
    var navOffset = $('#navbar').height();
    
    //animate the scroll
    return $('html, body').animate({
      scrollTop: $(this.hash).offset().top - navOffset
    }, 600, function() {
        //add hash to the end of URL
      return window.history.pushState(null, null, target);
    });
  });
*{
   margin: 0;
   padding: 0;
   box-sizing: border-box;
   font-family: 'Cormorant Garamond', serif;
   color: #B19BD9; 
}

#navbar {
    background: #B19BD9;
    text-transform: uppercase;
}

.navbar-dark .navbar-nav .nav-link {
    color: rgba(255,255,255,1);
    padding-right: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body data-spy="scroll" data-target="#navbar">
        <nav id="navbar" class="navbar navbar-expand-lg navbar-dark sticky-top">
          <a href="index.html" id="navbarBrand" class="navbar-brand">Stages of Change Counseling</a>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>

          <div id="navbarNav" class="collapse navbar-collapse">
            <ul class="navbar-nav ml-auto">
              <li class="nav-item">
                <a href="#home" class="nav-link">Home <span class="sr-only">(current)</span></a>
              </li>
              <li class="nav-item">
                <a href="#about" class="nav-link">About</a>
              </li>
              <li class="nav-item">
                <a href="#services" class="nav-link">Services</a>
              </li>
              <li class="nav-item">
                <a href="#approach" class="nav-link">Approach</a>
              </li>
              <li class="nav-item">
                <a href="#commitment" class="nav-link">Commitment</a>
              </li>
              <li class="nav-item">
                <a href="#contact" class="nav-link">Contact</a>
              </li>
            </ul>
          </div><!--navbarNav-->
        </nav>

        <main>
          <section id="home">
            <div class="container-fluid">
              <div class="row">
                <div class="col-12 px-0">
                  <img class="img-fluid" src="img/lotus.jpg" alt="Lotus flower">
                </div><!--col-->
                <div class="col-lg-10 col-10 mx-auto">
                  <p id="cta">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. .</p>
                </div>
                <div class="col-lg-6 col-10 mx-auto">
                  <p class="main-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
                </div><!--col-->
              </div><!--row-->
            </div><!--container-->
          </section>
          
          <section id="about">
            <div class="container-fluid">
              <div class="row">
                <div class="col-xl-5 offset-xl-1 col-12">
                  <img src="img/portrait.jpg" alt="A portrait of myself wearing a mint sweater and a flower flower pattern scarf" class="img-fluid d-block mx-sm-auto">
                </div><!--col-->
                <div class="col-xl-4 col-10 mx-auto">
                  <h1 class="header">About me</h1>
                  <p class="main-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                  <br><br>
                  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
                </div><!--col-->
              </div><!--row-->

              <div class="row">
                <div class="col-xl-8 col-10 mx-auto">
                  <p class="main-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                  <br><br>
                  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
                </div><!--col-->
              </div><!--row-->
            </div><!--container-->
          </section>
          
          <section id="approach">
            <div class="container-fluid">
              <div class="row">
                <div class="col-12">
                  <h1 class="header">Approach</h1>
                </div><!--col-->
                <div class="col-12 px-0">
                  <img src="img/staircase.jpg" alt="spiral staircase" class="img-fluid">
                </div>
                <div class="col-md-8 col-10 mx-auto">
                <p class="main-text">By listening deeply to each client before me, I strive to be fully present without preconceptions. By listening with an open heart to each person’s struggles, I pull from a lifetime of experience. Assessing which approaches may begin a particular client’s process of mitigating suffering may result in collaborating to start with a behavioral assignment, a cognitive restructuring process, dialoging with internal parts to release deeply held pain, or simply offering compassionate presence. The unique interaction between each individual and myself will yield different proscriptive approaches each time, <b>I definitely do not use a one size fits all approach.</b> Since healing often comes from a place of deep inner peace, behavioral homework may involve forms of meditation or relaxation to enhance systemic de-stressing. 
                <br><br>
                For the client’s part, awareness that change takes <b>effort</b>, is of paramount importance. Whatever a person’s configuration of functioning, it can usually only be changed, like building a wall or taking down a wall, brick by brick. That’s why my practice is called Stages of Change. Each person’s readiness to change and ability to apply focused, persistent effort unfolds at their own pace. As a wonderful teacher of mine said, “A therapist has maps but the client has to sit in the driver’s seat and put their foot on the gas.”
                <br><br>
                Albert Ellis used to have client’s put a banana on a leash and pull it down a crowded New York street to inoculate clients to what others’ thought of them! While few would relish a behavioral assignment like that, observation of the flow of one’s thoughts, courage to feel difficult feelings or journaling may help one know oneself at a deeper level. Surprising oneself with new capabilities built by taking risks can be deeply empowering. 
                </p>
                </div><!--col-->
              </div><!--row-->
            </div><!--container-->
          </section>


推荐阅读