所以我用一个简单的小脚本来练习我的JavaScript技巧,这个脚本会在点击时改变标题大小和颜色。当我在脚本标签内的HTML文档中运行JS时,它工作得很好,但是当我在浏览器中运行页面时,控制台会给我错误:“未捕获的TypeError:无法读取属性'addEventListener'的null - (匿名)功能)@ practice.js:13“
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
<link rel="stylesheet" href="main.css">
<script src="practice.js"></script>
</head>
<body>
<h1 id="main-heading">Hello</h1>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.</p>
</body>
</html>
CSS代码:
.red-text {
color: red;
font-size: 60px;
transition: 5s;
}
#main-heading {
font-size: 40px;
}
JavaScript代码:
// Creates "h" var, containing the main heading
var h = document.getElementById("main-heading");
// Creates a function that adds .red-text class to main heading
var addRedClass = function() {
h.className = h.className + " red-text";
};
// Activates the addRedClass function upon mouseover
h.addEventListener('click', addRedClass);
帮助?!
答案 0 :(得分:1)
您应该将javascript代码放在页面底部,如下所示:
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<h1 id="main-heading">Hello</h1>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.</p>
<p class="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.</p>
<script src="practice.js"></script>
</body>
</html>
因为当您在头部调用document.getElementById("main-heading")
时,文档中没有main-heading
元素,头部已加载,因此您应将javascript代码放在底部或使用{{1}功能。