Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery平滑滚动,仅当锚点链接是id时执行_Jquery - Fatal编程技术网

jQuery平滑滚动,仅当锚点链接是id时执行

jQuery平滑滚动,仅当锚点链接是id时执行,jquery,Jquery,我已经使用jQuery编写了一个平滑滚动函数。 但是有一个问题 如果锚点在href中只有散列,则返回未定义的错误。 比如: 请告诉我如何运行我的函数只有当锚链接是一个ID,而不是如果只有散列 这是我的功能: //平滑卷轴 jQuery('a[href^="#"]').click(function (e) { e.preventDefault(); var target = this.hash; jQuery('html, body').a

我已经使用jQuery编写了一个平滑滚动函数。 但是有一个问题

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

请告诉我如何运行我的函数只有当锚链接是一个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('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);
            }  
        }
    });
});  
你应该给你想要的锚定一个特定的类,而不是像上面那样针对每一个锚定

试试这个:

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

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

这是我的代码

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

请分享我的单线最小解决方案:

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