Javascript 无法读取未定义jQuery错误的属性“top”
我有以下代码:Javascript 无法读取未定义jQuery错误的属性“top”,javascript,jquery,undefined,Javascript,Jquery,Undefined,我有以下代码: $('body').scrollspy({ target: '.sidebar > .nav > .active', offset: 120 }); /* animate scrolling to the sidebar sublink targets to ensure proper offsets */ $('.sidebar > .nav > .active > .nav > li > a').on('click',
$('body').scrollspy({
target: '.sidebar > .nav > .active',
offset: 120
});
/* animate scrolling to the sidebar sublink targets to ensure proper offsets */
$('.sidebar > .nav > .active > .nav > li > a').on('click', function () {
var target = $($(this).attr('href'));
$('html, body').animate({
scrollTop: target.offset().top
}, 200);
});
我得到以下错误
未捕获的TypeError:无法读取未定义的属性“top”
在兰开夏。site.js?v=6-PQc6gnbrcv8oGPmVGKbiMSOAf5yrI5zG6Eeo7i360:81
在htmlanchorement.dispatch jquery-2.2.0.min.js:3
在htmlanchorement.r.handlejquery-2.2.0.min.js:3
我猜你没有选择你想要的。也许a不是目标。可能您没有使用等于href的选择器选择要选择的节。也许答案不是你所想的。也许偏移量没有定义,因为jQuery无法计算它
$('body').scrollspy({
target: '.sidebar > .nav > .active',
offset: 120
);
$('.sidebar > .nav > .active > .nav > li > a').on('click', function () {
var href = $(this).attr('href') || $('a', this).attr('href'),
target = $(href);
console.log('Href:', href);
console.log('Target:', target);
console.log('Offset:', target.offset());
target.length && target.offset() && $('html, body').animate({
scrollTop: target.offset().top
}, 200);
});
因为他们说:
注意:jQuery不支持获取隐藏元素>的偏移坐标,也不支持计算文档元素上设置的边距
虽然可以使用visibility:hidden>set获取元素的坐标,但display:none从渲染树中排除,因此具有未定义的位置>>
问题是因为目标中的jQuery对象不包含任何元素。我们无法确切地告诉您这是为什么,除非您看到单击的a元素的href中的值,或者您的其他元素中的值HTML@RoryMcCrossan啊,我查过了,,我查看了示例,看到了offset.left示例-如上所示,它将offset预定义为offset haha将删除注释。还有一个快速问题-在$this.attr'href'上执行$$this.attr'href'有什么好处?$this.attr'href'返回一个字符串$$this.attr'href'返回一个jQuery对象,使用href作为选择器,我看到了ok,谢谢@rorymcrossan!上面脚本的结果是:Href:colors-Target:n.fn.init{context:document,selector:colors}Offset:undefined Href:colors-Target:n.fn.init{context:document,selector:colors}Offset:undefinedTry-to-exo和目标后面的对象:查看长度是0还是1。当你复制粘贴到这里的时候,数据会被丢弃ffs:你有一些id=colors的html元素吗?我有一个id为的链接=colors@dewilde86在检查其偏移量时是否可见?