我使用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);
});发布于 2013-05-11 10:46:12
你可以试着做:
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-11 10:52:18
试试这个:
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-11 11:18:51
我得到了这个问题的小解决方案,只需检查目标是否未定义,如果是,就不要运行它。
这里是我的代码
//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);
}
});https://stackoverflow.com/questions/16496190
复制相似问题