![](/img/trans.png)
[英]This javascript code is running properly without the for loop but not with it.Any help, I have tried everything
[英]Javascript not Running Correctly - Tried Everything
我的 javascript 只有一行代碼,它得到“getElementById null”錯誤。
document.getElementById("menu-background").style.left = "0";
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:
#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;
}
我運行 Visual Studio 代碼並檢查了 js 的鏈接。 我還嘗試在 HTML 文件中運行它。
你可以試試這個:
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById("menu-background").style.left = "0";
});
您應該將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>
我發現問題了!!!
我的 HTML 文件被命名為“main.html”,當我將它重命名為“index.html”時它起作用了!
感謝你們的快速回復,伙計們。 我是新來的,所以我是認真的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.