【问题标题】:jQuery smooth scroll, do only if anchor link is an idjQuery 平滑滚动,仅当锚链接是 id 时才执行
【发布时间】:2013-05-05 23:02:57
【问题描述】:

我使用 jQuery 编写了一个平滑滚动功能。 但是有个问题,

如果anchor只有href中的hash,那么它会返回未定义的错误。 喜欢:

<a href="#" title="something">Link</a>

请告诉我如何运行我的函数,只有当锚链接是一个 ID 而不是只有散列时。

这是我的功能:

//平滑滚动

jQuery('a[href^="#"]').click(function (e) {    
        e.preventDefault();
        var target = this.hash;
        jQuery('html, body').animate({ 
                  scrollTop: (jQuery(target).offset().top) - 60 
                }, 1000);    
});

【问题讨论】:

    标签: jquery


    【解决方案1】:

    试试这个:

    jQuery('a').click(function (e) {
        e.preventDefault();
        var target = this.hash;
        if (this.href != '#') {
            jQuery('html, body').animate({
                scrollTop: jQuery(target).offset().top - 60
            }, 1000);
        }
    });
    

    【讨论】:

      【解决方案2】:

      你可以尝试这样做:

      jQuery('a').each( function() {
          var $this = jQuery(this), 
              target = this.hash;
          jQuery(this).click(function (e) { 
              e.preventDefault();
              if( $this.length > 0 ) {
                  if($this.attr('href') == '#' ) {
                      // Do nothing   
                  } else {
                     jQuery('html, body').animate({ 
                          scrollTop: (jQuery(target).offset().top) - 60 
                      }, 1000);
                  }  
              }
          });
      });  
      

      你应该给你想要的锚一个特定的类,而不是像上面那样针对每个锚。

      【讨论】:

        【解决方案3】:

        我得到了这个问题的小解决方案, 只需检查目标是否未定义,如果是则不要运行它。

        这是我的代码

        //smooth scroll
        jQuery('a[href^="#"]').click(function (e) {
            e.preventDefault();
            var target = this.hash;
        
            if (typeof(jQuery(target).offset()) != 'undefined') {
                jQuery('html, body').animate({
                    scrollTop: jQuery(target).offset().top - 60
                }, 1000);
            }
        });
        

        【讨论】:

          【解决方案4】:

          只是为了分享我的单行最小解决方案:

          $('a[href^="#"]').click(function(e){e.preventDefault();var o=$(this.hash).offset();if(o)$('body').animate({scrollTop:o.top})})
          

          仅在 chrome 上测试

          【讨论】:

            猜你喜欢
            • 2013-07-17
            • 1970-01-01
            • 2021-12-25
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多