简单的放松引导滚动间谍

Simple easing on bootstrap scrollspy

本文关键字:滚动 间谍 简单      更新时间:2023-09-26

我认为对于那些熟悉javascript/jquery的人来说,这是一个非常简单的问题。我对这一切都很陌生,无法做到。我发现计算导航栏偏移量的代码看起来像这样:

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

这是目前为止我所拥有的最简单的例子。你可以看到,如果你点击导航栏中的链接它会跳转到section。在这个脚本中添加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;
});

这有帮助吗?