【问题标题】:Javascript - scroll effect interferes with linksJavascript - 滚动效果会干扰链接
【发布时间】:2015-11-10 05:15:15
【问题描述】:
$('body a').click(function(e){
e.preventDefault();
var goTo = $(this).attr('href').replace('#','');
$("html, body").animate({
scrollTop:$('a[name="'+goTo+'"]').offset().top
},1100);
window.location.hash = "#"+goTo;
});
我的 javascript 代码可以正常工作,但当我尝试点击链接时出现此错误:
TypeError: $(...).offset(...) 未定义
【问题讨论】:
标签:
javascript
scroll
hyperlink
anchor
【解决方案1】:
这是因为 e.preventDefault();
它会阻止链接工作,并将其设置为正文中的所有标签
尝试使用另一个脚本
【解决方案2】:
尝试:
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
|| location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1100);
return false;
}
}
});