javascript 无法读取 null 错误的属性“addEventListener”,不知道为什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23072007/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:17:05  来源:igfitidea点击:

Cannot read property 'addEventListener' of null Error, not sure why

javascript

提问by user3533879

Whenever I hover over the image it does not enlarge and gives an error.

每当我将鼠标悬停在图像上时,它都不会放大并出现错误。

HTML and Javascript code(these are two separate files):

HTML 和 Javascript 代码(这是两个单独的文件):

var banner = document.getElementById("banner");

function enlargePic(){
banner.style.width = '800px';
banner.style.height  = '300px';
}

function normalPic(){
banner.style.width = '500px';
banner.style.height  = '200px';
}


banner.addEventListener("mouseover", enlargePic, false); 

banner.addEventListener("mouseout", normalPic, false); 

<div id="designs">
<a id="designs"></a>
<h1>DESIGNS.</h1> 
<table>
<tr>
<td><img src="banner2.jpg" id="banner"></td>
</tr>
</table>
</div>

回答by Matricore

Your javascript code is in your first section. So it has rendered before banner element and cannot find the element id = banner because it has not rendered yet. Try to locate the code before the html code.

您的 javascript 代码在您的第一部分。所以它已经在banner元素之前渲染了并且找不到元素id=banner,因为它还没有渲染。尝试将代码定位在 html 代码之前。

回答by Treacle

When referencing the function normalpic, you should preceed it with an empty function:

当引用函数 normalpic 时,你应该在它前面加上一个空函数:

banner.addEventListener("mouseout",function(){normalpic},false)