javascript - bootstrap scrollspy 上的简单缓动

标签 javascript jquery twitter-bootstrap easing scrollspy

我认为对于那些非常了解 javascript/jquery 的人来说,这是一个非常简单的问题。我对这一切都很陌生,无法做到。我找到了计算导航栏偏移量的代码,如下所示:

var offset = 50;

$('.navbar li a').click(function(event) {
event.preventDefault();
$($(this).attr('href'))[0].scrollIntoView();
scrollBy(0, -offset);

});

这里是 fiddle example我到目前为止所拥有的。如您所见,如果您单击导航栏中的链接,它只会跳到该部分。在此脚本中的何处添加 easing 以便向下滚动更顺畅一些?

使用原始代码,我首先发现我有平滑的滚动,但使用新脚本时丢失了。这是旧代码:

$(function() {
$('a.page-scroll').bind('click', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top
    }, 1500, 'easeInOutExpo');
    event.preventDefault();
});
});

最佳答案

Plavookac 你好。
我在这个 Fiddle 中设置了一个工作示例 为你。
当您将这段代码放在您的页面中时,将它放在所有其他 js 脚本链接的下方。或者,如果您将它放在脚本链接中,请将链接放在末尾。 我认为您已经有了 jquery 链接。

看看这段代码,你会看到平滑的滚动和偏移。

$(document).ready(function(){
  // Add scrollspy to <body>   
  $('body').scrollspy({target: "#navbar"}); 

  // Add smooth scrolling on all links inside the navbar
  $("#navbar a").on('click', function(event) {
    // 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 - 60
    }, 800, function(){

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

注意这行代码... event.preventDefault(); 这用于防止第一次单击开始滚动时出现闪烁。

这部分代码将处理平滑滚动

// 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 - 60
    }, 800, function(){

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

这有帮助吗?

关于javascript - bootstrap scrollspy 上的简单缓动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32922813/

相关文章:

javascript - 在 Sequelize-CLI 中仅恢复两个迁移之一?

javascript - Vue.js 2 : Conditional Rendering not working

jquery - tinymce 与 jquery ajaxsetup datafilter 不兼容

javascript - 如何使用 jQuery 从 html 字符串中提取多个部分?

jquery - 多个 jQuery 函数和自动完成

css - 添加 bootstrap nav-pills 背景颜色

html - 更改不同屏幕上的列顺序

html - 模态对话框关闭图标与 CSS 对齐

javascript - Bootstrap 工具提示标题中的 anchor 链接在点击时不像 anchor

javascript - 如何在 react 中无限发送请求而不渲染整个组件以进行实时提要