Javascript 错误Scrolltop:未定义top
我得到以下错误 未捕获的TypeError:无法读取未定义的属性“top” 这是关于站在这一行的Javascript 错误Scrolltop:未定义top,javascript,jquery,Javascript,Jquery,我得到以下错误 未捕获的TypeError:无法读取未定义的属性“top” 这是关于站在这一行的顶端的:$(html,body),1000,函数,但我真的不知道如何修复此错误。我已经尝试过多个有类似问题的帖子,但到目前为止没有一个能解决我的问题 // Menu Scroll to content and Active menu var lastId, topMenu = $("#menu"), topMenuHeight = topMenu.outerHeight() + 145,
顶端的:$(html,body),1000,函数
,但我真的不知道如何修复此错误。我已经尝试过多个有类似问题的帖子,但到目前为止没有一个能解决我的问题
// Menu Scroll to content and Active menu
var lastId,
topMenu = $("#menu"),
topMenuHeight = topMenu.outerHeight() + 145,
menuItems = topMenu.find("a"),
scrollItems = menuItems.map(function() {
var item = $($(this).attr("href"));
if (item.length) {
return item;
}
});
$('a[href*=#]').bind('click', function(e) {
e.preventDefault();
var target = $(this).attr("href");
$('html, body').stop().animate({
scrollTop: $(target).offset().top - 60
}, 1000, function() {});
return false;
});
$(window).scroll(function() {
var fromTop = $(this).scrollTop() + topMenuHeight;
var cur = scrollItems.map(function() {
if ($(this).offset().top < fromTop)
return this;
});
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
menuItems
.parent().removeClass("active")
.end().filter("[href=#" + id + "]").parent().addClass("active");
}
});
//菜单滚动至内容和活动菜单
var lastId,
topMenu=$(“#菜单”),
topMenuHeight=topMenu.outerHeight()+145,
menuItems=topMenu.find(“a”),
scrollItems=menuItems.map(函数(){
var item=$($(this.attr(“href”));
如果(项目长度){
退货项目;
}
});
$('a[href*=#]')。绑定('click',函数(e){
e、 预防默认值();
var target=$(this.attr(“href”);
$('html,body').stop().animate({
scrollTop:$(目标).offset().top-60
},1000,函数(){});
返回false;
});
$(窗口)。滚动(函数(){
var fromTop=$(this.scrollTop()+topMenuHeight;
var cur=scrollItems.map(函数(){
if($(this).offset().top
您正试图从.attr('href')
获取偏移量
尝试删除.attr('href')代码>
或
由于选择器具有$('a[href*=#]
,因此href可能包含的不仅仅是#id
,而是/foo/bar#id
。因此,请尝试:-
var target = $(this).attr("href").split('#')[1];
$('html, body').stop().animate({
scrollTop: $('#' + target).offset().top - 60
}, 1000, function() {});
未定义的不是top
,而是您尝试访问其属性top
的元素。按照此属性的标准模式,如果href
是有效的选择器,例如href=“#bookmark”
,则此代码将有效。如果看不到HTML,很难说。谢谢你指出@Rorymcrossan,我已经更新了我的答案。谢谢你的输入。问题已解决,不再出现错误!
var target = $(this).attr("href").split('#')[1];
$('html, body').stop().animate({
scrollTop: $('#' + target).offset().top - 60
}, 1000, function() {});