簡體   English   中英

Simon.js:未捕獲的TypeError:無法讀取null的屬性“樣式”

[英]Simon.js: Uncaught TypeError: Cannot read property 'style' of null

我知道您可能會發現這是重復的,但對我來說,任何答案都沒有用。 我正在像假期項目之類的Simon程序中工作,但是此JavaScript代碼的第41行遇到了問題。 事實是,在HTML文件中,id存在,但也變為“ null”:

var pccolor = [];
var usercolor = [];

function SimonStart() {

    document.getElementById("start").style.opacity = .3;

MakeColors();
}

function MakeColors() {

    var colors = [1, 2, 3, 4, 6, 7, 8, 9];
    var randcolor = colors[Math.floor(Math.random() * colors.length)];
    pccolor.push(randcolor);
    LightColor(randcolor, 1000);

}

var randcolor;
var s;

function LightUp() {

    LightColor(pccolor[s]);
    s++;

    if (s < pccolor.length) {

        setTimeout(function () {
            LightUp();

        }, 500);

    }
}

function LightColor(color, TimeOut) {

    var TimeOut = 1000;
    document.getElementById("c" + color).style.opacity = "1"; //doesn't work!
    setTimeout(function () {

        document.getElementById("c" + color).style.opacity = ".3";

    }, TimeOut);

}

function Button(OnClick) {

    LightColor(OnClick);
    usercolor.push(OnClick);
    var i = usercolor.length - 1;
    if (pccolor[i] != usercolor[i]) {

        setTimeout(function () { alert("You lose!"); }, 300);
        pccolor = [];
        usercolor = [];

    } else if (pccolor.length == usercolor.length) {

        usercolor = [];
        pccolor.push(randcolor);
        s = 0;
        setTimeout(function () {

           LightUp();
        }, 500);

    }
}

這是.js文件的結尾,而這是HTML文件:

<!DOCTYPE html>
<html>
<head>
...

<script type="text/javascript" src="Simon.js"></script>

<link rel="stylesheet" type="text/css" href="Simon.css">

</head>

<body>
    <div class="centerDiv"> 
        <div class="negro">
            <div class="color" id="c1" onclick="Button (1);"> </div>
            <div class="color" id="c2" onclick="Button (2);"> </div>
            <div class="color" id="c3" onclick="Button (3);"> </div>
        </div>
        <div class="negro">
            <div class="color" id="c4" onclick="Button (4);"> </div>
            <div class="color" id="start" onclick="SimonStart ();"></div>
            <div class="color" id="c6" onclick="Button (6);"> </div>
        </div>
        <div class="negro">
            <div class="color" id="c7" onclick="Button (7);"> </div>
            <div class="color" id="c8" onclick="Button (8);"> </div>
            <div class="color" id="c9" onclick="Button (9);"> </div>
            </div>
    </div>

</body>
</html>

有人可以幫我嗎?

將所有腳本標簽放在HTML文件的末尾。

您的代碼實際上是在加載DOM之前執行的,因此對於JavaScript程序而言,沒有HTML可以處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM