aba*_*ass 2 html javascript navigation anchor jquery
我的一切都在我的网站上完美运行,但出于某种原因,每当我点击我网站上任何地方的链接时,我都会在控制台中收到错误消息.该错误与此处的编码行有关:
jQuery(function($){
$('.navbar a, .scroll a, .smoothscroll a').bind('click',function(event){
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 850,'easeInOutExpo');
event.preventDefault();
});
});
Run Code Online (Sandbox Code Playgroud)
我得到的错误是这样的:
"SCRIPT5007:无法获取属性'top'的值:对象为null或未定义custom.min.js,第6行字符197"
它突出显示的确切代码是上面代码的这一部分:
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 850,'easeInOutExpo')
Run Code Online (Sandbox Code Playgroud)
我所知道的是,当我删除上面的代码时,我的滚动链接停止在以下页面上工作:
http://www.northtownsremodeling.com/things-to-know.php
您可以看到弹出错误发生并通过转到带有这样的过滤器的页面轻松地保留在控制台中:
http://www.northtownsremodeling.com/bathroom/
然后单击其中一个过滤器按钮.
最终,我试图让它滚动到设置仍然有效,但不再出现错误.很久以前我制作了这个剧本,我真的很困惑,当一切都运转正常时,可能导致这个错误的原因是什么?
谢谢!
你遇到的问题是,给出错误的代码是滚动到预定义的div,你在url的hashtag(你点击的链接的href属性)中有你的id(目标div).
单击"普通"链接时会出现问题,因为它不包含hashpage,它是页面上存在的元素的id,所以$($anchor.attr('href'))给出空数组,因为没有这样的元素可以选择ie $("http://www.northtownsremodeling.com/alliances.php"),因此,在这种情况下偏移()未定义并给出错误.
要解决此问题,请替换:
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 850,'easeInOutExpo');
Run Code Online (Sandbox Code Playgroud)
有:
// get target div to scroll to
var target = $($anchor.attr('href'));
// if target is valid, scroll to
if(target && target.offset()){
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 850,'easeInOutExpo');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2985 次 |
| 最近记录: |