javascript 获取未捕获的类型错误:无法在 js 中读取 null 的属性“left”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10338829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting Uncaught TypeError: Cannot read property 'left' of null in js
提问by Rodney Wilson
I have this jquery code that goes through the nav bar and the selected link has a box around it. It only works on the middle link, none of the others. Any ideas? Thanks in advance.
我有这个通过导航栏的 jquery 代码,所选链接周围有一个框。它仅适用于中间链接,其他链接均无效。有任何想法吗?提前致谢。
navigation arrow starts
var $el, leftPos, newWidth,
$mainNav = $("#nav");
$mainNav.append("<li id='magic-line'></li>");
var $magicLine = $("#magic-line");
$magicLine
.width($(".current_page_item").width())
.css("left", $(".current_page_item a").position().left)
.data("origLeft", $magicLine.position().left)
.data("origWidth", $magicLine.width());
//scroll arrow
function update_location(){
$el = $('#nav').children('li.current');
leftPos = $el.position().left;
newWidth = $el.width();
$('#nav li:nth-child(4) a').addClass('button-style');
if(window.top.scrollY == 0)
{
setTimeout(function(){
$magicLine.stop().animate({
left: 8,
width: 355
});},1000);
$('#nav li:nth-child(4) a').removeClass('button-style');
}
else
{
setTimeout(function(){
$magicLine.stop().animate({
left: leftPos,
width: newWidth
});},1000);
}
}
$('#magic-line').css('left', '-15px', 'width','411px');
$(window).scroll(function(){
update_location();
});
<div class="navbar-fixed-top navbar" >
<div class="navbar-inner">
<div class="container">
<ul class="nav nav-pills pull-right" id="nav">
<li class="current_page_item" style="width: 355px;"><a href="#home" class="logo" style="display:block; width: 355px;"><img src="images/logo.jpg" class="current_page_item" width="355" alt="" /></a></li>
<li><a href="#vision">VISION</a></li>
<li><a href="#services">SCHOOLS</a></li>
<li><a href="#apply">REQUEST AN EVALUATION</a></li>
<li><a href="#how-it-works">HOW IT WORKS</a></li>
<li><a href="#contact-us">CONTACT US</a></li>
</ul>
</div>
</div>
</div>
Getting the error after leftPos = $el.position().left;
under function update_location()
leftPos = $el.position().left;
下后得到错误function update_location()
采纳答案by Adam
I think you might be meaning to use the class current_page_item instead of current on this line:
我认为您可能想在这一行使用类 current_page_item 而不是 current :
$el = $('#nav').children('li.current');
$el is an empty jQuery object so el.position() is null and hence, cannot read property left of null.
$el 是一个空的 jQuery 对象,因此 el.position() 为 null,因此无法读取 null 左侧的属性。
回答by daker
Thats because:
那是因为:
$el = $('#nav').children('li.current');
returns null.
返回空值。
Try:
尝试:
$el = $('#nav').children('li.current_page_item');