【问题标题】:Prevent Default behavior for Bootstrap 4 javascript scroll-spy in a rails application防止 Rails 应用程序中 Bootstrap 4 javascript scroll-spy 的默认行为
【发布时间】:2016-12-26 19:04:01
【问题描述】:

我正在构建一个 rails 5 应用程序,并且我正在尝试向我的登录页面添加一个带有 scrollspy 的导航栏。按照 bootstrap 4 文档,我附加了一个带有 javascript 的 scrollspy。但是,当我单击导航栏中的某个链接时,有时会出现闪烁。我相信这是由于默认行为,我需要在 jQuery 中调用 event.preventDefault() 。

我是 jQuery 新手,这可能是一个非常简单的问题,但我该怎么做呢?在 bootstrap 4 文档 http://v4-alpha.getbootstrap.com/components/scrollspy/#example-in-navbar 中,他们在 javascript 部分下提到要添加滚动间谍,只需执行以下操作:

$('body').scrollspy({ target: '#myNavbar' })

当我将它包装在 turbolink 要求中时,它工作得很好:

$(document).on('turbolinks:load', function() {
      $('body').scrollspy({ target: '#myNavbar' })
});

但是,我不确定如何将事件传递给它以防止闪烁发生。

谢谢!

【问题讨论】:

标签: javascript jquery ruby-on-rails twitter-bootstrap scroll


【解决方案1】:
$(document).on('turbolinks:load', function(){
  $('body').scrollspy({target: "#myNavbar"});

  // Add smooth scrolling on all links inside the navbar
  $("#myNavBar 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
      $('.scrollbar,body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

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

信用:Bootstrap JS Scrollspy into a Bootstrap panel

【讨论】:

  • 谢谢!这有很大帮助
猜你喜欢
  • 2021-08-07
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多