0

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

如果锚点在 href 中只有散列,则返回未定义的错误。喜欢:

<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);    
});
4

4 回答 4

4

尝试这个:

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);
    }
});
于 2013-05-11T10:52:18.557 回答
3

你可以尝试这样做:

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);
            }  
        }
    });
});  

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

于 2013-05-11T10:46:12.233 回答
0

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

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

仅在 chrome 上测试

于 2013-08-20T08:27:38.043 回答
0

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

这是我的代码

//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);
    }
});
于 2013-05-11T11:18:51.230 回答