[英]Cannot read property 'addEventListener' of null - JavaScript
I have never used JavaScript or CSS before.我以前从未使用过 JavaScript 或 CSS。 I have used Actionscript and I find it similar to JavaScript.
我使用过 Actionscript,我发现它类似于 JavaScript。
I am making a small html page where there is a fadeInUp animation from animation.css我正在制作一个小的html页面,其中有来自animation.css的fadeInUp动画
I wanted to do the animation myself, instead of animation.css doing it for me, for practice.我想自己做动画,而不是 animation.css 为我做,为了练习。
I did everything right, except the animation does not stay at the end opacity, it resets to the css-coded opacity.我做的一切都正确,除了动画不会停留在最后的不透明度,它会重置为 css 编码的不透明度。
I decided to do some javascripting and made this code我决定做一些 javascripting 并制作了这段代码
(the div that the two animated elements are in is called "toppart") (两个动画元素所在的div称为“toppart”)
var beginpart = document.getElementById("toppart");
beginpart.addEventListener("animationend", giveopac, false);
function giveopac()
{
this.style.opacity=1
}
I do not know what is wrong with it (probably something wrong with syntax), but I get this console error:我不知道它有什么问题(可能是语法有问题),但我收到了这个控制台错误:
Uncaught TypeError: Cannot read property 'addEventListener' of null
(anonymous function)
Is the problem with the function or is it with variable?是函数的问题还是变量的问题? If something is wrong with the event listener, there are about 10 websites that are wrong.
如果事件侦听器有问题,大约有 10 个网站是错误的。
If anybody knows what I am doing wrong, and why it is giving me the error, I would love to know.如果有人知道我做错了什么,以及为什么给我错误,我很想知道。
If it is still not working it is because in the giveopac event you are trying to access this and adding style to it which is not right.Here this is window object You might consider changing this check the following code snippet如果它仍然不起作用,那是因为在 giveopac 事件中,您试图访问它并向其添加样式,这是不对的。这是窗口对象您可以考虑更改此检查以下代码片段
var beginpart = document.getElementById("toppart"); // alert(beginpart); beginpart.addEventListener("animationend", giveopac, false); function giveopac(event) { event.target.style.opacity=1; event.target.style.background="red"; }
<body> <div id="toppart"> <p id="first" class="moveupfade">Zane Clark</p> <p id="subfirst" class="moveupfade">"Keter"</p> </div> </body>
Hope this helps;希望这可以帮助;
Found the answer!找到答案了!
I put it after the whole body and changed it to this:我把它放在全身之后,改成这样:
<script>
document.getElementById("toppart").addEventListener("animationend", giveopac);
function giveopac(event)
{
event.target.style.opacity=1;
}
</script>
Thanks to geeky感谢极客
Make sure that you have your script tags before closing tag of body in html page.在关闭 html 页面中的 body 标签之前,请确保您有脚本标签。
<html>
<body>
<div id="toppart"> <p id="first" class="moveupfade">Zane Clark</p> <p id="subfirst"
class="moveupfade">"Keter"</p> </div>
<script src="myScript.js"></script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.