导航栏特定的 jQuery 滚动动画

Navbar Specific jQuery Scroll Animation

本文关键字:jQuery 滚动 动画 导航      更新时间:2023-09-26

我有一个固定的标题,其中有一些链接。现在,这段代码几乎是我需要它工作的地方,主要问题是执行第二个函数时有延迟。它的预期目的是在单击绑定元素时滚动到页面顶部,但它一开始会缓慢地滚动,然后再以指定的速度继续。我相信还有一种方法可以 DRY 它并将其转换为单个函数而不是两个单独的函数。任何帮助将不胜感激。

$(function() {
  $("[href^='#']").on("click", function( e ) {  
    $("body, html").animate({ 
      scrollTop: $( $(this).attr('href') ).offset().top-$('.header').height()-$('.header').outerHeight()
    }, 800); 
    e.preventDefault();
  });    
});

$(function(){
    $("#home").on("click", function( e ){
        $("body, html").animate({
            scrollTop: 0
        }, 800);
        e.preventDefault();
    });
});

JSFiddle - http://jsfiddle.net/9by4n5cu/1/

你可以像波纹管一样合并两个函数,

  $(function() {
    $("[href^='#']").on("click", function( e ) {  
      var target = $(this).attr('href');
      var scrollTop = $( target ).offset().top-$('.header').height()-$('.header').outerHeight();
      if ( target =='#home'){
         scrollTop = 0;
      }
      $("body, html").animate({
              scrollTop: scrollTop
          }, 800);
      e.preventDefault();

    });
  });

演示:http://jsfiddle.net/ibrahim12/9by4n5cu/3/

它延迟是因为您触发了两次animate,所以就像您所说的那样,您需要将function合并为这样的

一个
$(function () {
    $("[href^='#']").on("click", function (e)  {
        var link = $(this);
        var $header = $('.header')
        var top = link.attr("id") == "home" ? 0 : $(link.attr('href')).offset().top - $header.height() - $header.outerHeight()
        //$("html").animate({
        $("body, html").animate({    // Use $("body, html") to work on all browser as noted by Ibrahim
            scrollTop: top
        }, 800);
        e.preventDefault();
    });
});

我使用第一次点击功能,然后检查点击link的 id 是否home,如果是,则将top设置为 0,否则像以前一样进行计算。

这是更新的小提琴小提