JS Scrolling似乎无法在我的网站上运行

时间:2017-12-07 13:07:07

标签: javascript jquery html css smooth-scrolling

所以我试图使用此模板中使用的平滑滚动动画:

https://blackrockdigital.github.io/startbootstrap-scrolling-nav/

将js文件添加到我的目录(包括基本JQuery文件)之后,我发现添加滚动的自定义.js文件使用锚标记中的.class参数来检测是否单击它应该触发smoothscrolling。所以我将这些添加到我的锚标签中。

以下是相关代码。

我也会包含一个实时预览。

index.html文件

<!-- Navigation section -->
<section class="nav" id="nav">
    <div class="container">
        <div class="row" style="width: 100%; text-align: center;">
            <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                <a class="js-scroll-trigger btn btn-lg btn-nav" href="#about">About me</a>
            </div>

            <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                <a class="js-scroll-trigger btn btn-lg btn-nav" href="#work">My work</a>
            </div>

            <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                <a class="js-scroll-trigger btn btn-lg btn-nav" href="#contact">Contact</a>
            </div>
        </div>
    </div>  
</section>

在index.html中导入脚本

<!-- Import js -->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="js/scrolling-nav.js"></script>

滚动-nav.js

(function($) {
  "use strict"; // Start of use strict

  // Smooth scrolling using jQuery easing
  $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, "easeInOutExpo");
        return false;
      }
    }
  });

})(jQuery); // End of use strict

我几乎没有JQuery / JS的经验,所以我很难理解它可能出错的地方。

以下是网站的实时预览,其中包含以上代码:

Live preview

完整代码:

Github link

如果缺少任何信息,请与我们联系。

2 个答案:

答案 0 :(得分:0)

缺少jQuery,你在点击事件中使用了jQuery ......

enter image description here

答案 1 :(得分:0)

在jquery中添加此代码

    $(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});