[英]Javascript not Running Correctly - Tried Everything
My javascript only has one line of code, and it gets the "getElementById null" error.我的 javascript 只有一行代码,它得到“getElementById null”错误。
document.getElementById("menu-background").style.left = "0";
HTML: HTML:
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="main.css" />
<script type="text/javavascript" src="js/main-menu.js"></script>
</head>
<body>
<div id="menu-background">
<div id="main-menu"></div>
</div>
</body>
</html>
CSS: CSS:
#menu-background {
position: fixed;
width: 100%;
height: 100%;
background-image: url("images/background.png");
background-position: center;
background-size: cover;
top: 0;
text-align: center;
left: 100%;
}
#main-menu {
width: 60vw;
height: 80vh;
border-style: solid;
border-radius: 1.125em;
border-color: #b88a00;
margin: auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(0, 0, 0, 0.75);
transition: all 0.25s;
}
I run visual studio code and have checked the link to the js.我运行 Visual Studio 代码并检查了 js 的链接。 I have also tried to run it inside of the HTML file.
我还尝试在 HTML 文件中运行它。
You can try this:你可以试试这个:
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById("menu-background").style.left = "0";
});
You should put your script
at the end of the document in order for the element to be defined before reaching it:您应该将
script
放在文档的末尾,以便在到达之前定义元素:
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body>
<div id="menu-background">
<div id="main-menu"></div>
</div>
<script type="text/javavascript" src="js/main-menu.js"></script>
</body>
</html>
I have found the problem!!!我发现问题了!!!
My HTML file was named "main.html" and when I renamed it to "index.html" it worked!我的 HTML 文件被命名为“main.html”,当我将它重命名为“index.html”时它起作用了!
Thanks for the fast replies, guys.感谢你们的快速回复,伙计们。 I'm a newcomer here, so I really mean it.
我是新来的,所以我是认真的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.