未捕获类型错误:无法仅在本地读取属性

时间:2014-05-19 10:41:32

标签: javascript jquery

我的javascript中只有在本地运行时出错,但是当我在jsfiddle上运行时它运行正常。

的Javascript

var pos, scrollY, 
    $el               = $('nav'),
    navItems          = $el.find('> span'),
    menuHeight        = $el[0].clientHeight,
    sections          = $('section').toArray(),  // cache elements
    pointOfAttachment = $el[0].getBoundingClientRect().top;

// Bind events
$(window).on('scroll.nav', updateNav)
         .on('resize.nav', updateNav);

function updateNav(){
    scrollY = window.pageYOffset || document.documentElement.scrollTop;

    for( var i = sections.length; i--; ){
        if( sections[i].getBoundingClientRect().top - menuHeight < 0 ){
            navItems.filter('.' + sections[i].id).addClass('active').siblings().removeClass('active');
            break;
        }
        navItems.removeClass('active');
    }

    if( scrollY > pointOfAttachment )
        $el.addClass('fixed');
    else
        $el.removeClass('fixed');
}

// for initial page load
updateNav();

$("nav span").click(function() {
    var sectionId = $(this).attr('class')
    $('html, body').animate({
        scrollTop: ($('#'+sectionId).offset().top - $('nav').height()) + 1
    }, 300);
});

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript">
</script>
<script src="script.js" type="text/javascript">
</script>
<title></title>
</head>
<body>
<header>Header</header>
<nav>
  <span class='a1'>Section 1</span>
  <span class='a2'>Section 2</span>
  <span class='a3'>Section 3</span>
</nav>
<div id='navPlaceholder'></div>

<section id='a1'>Some section..</section>
<section id='a2'>Another Section</section>
<section id='a3'>And another one</section>
</body>
</html>

当我在JSfiddle上运行它时工作正常但是当我在本地运行时我得到了javascript错误:

  

未捕获的TypeError:无法读取未定义的属性“clientHeight”

任何人都可以告诉我为什么这只会在本地发生,我可以解决它吗?

1 个答案:

答案 0 :(得分:1)

一旦DOM准备好,您应该包括script

   <script src="script.js" type="text/javascript">
</body>

例如,就在</body>结束标记

之前