簡體   English   中英

如何在 Javascript 中動態更新背景圖像大小

[英]How to update the background-image size dynamically in Javascript

我是編程新手,目前正在嘗試我的第一個迷你項目——一個單詞定義游戲。

我在輸入字段上有一個事件偵聽器,每次達到某個分數時都會更改背景圖像。 我的問題是,每次更改背景圖像時,都會丟失 CSS 樣式屬性,即backgroundSize = cover; .

我做了一個 function 將backgroundSize值更改為cover ,這只有在我在控制台中調用它時才有效。 我也試過內聯 styles,沒有效果。

我只是無法讓它通過 javascript 文件(既不是eventListener也不是 if 語句)工作。

加載的圖像始終設置為auto ,我需要將其設置為“封面”。

任何幫助將不勝感激。

body {
    background: url("/IMG/moebius.jpg");
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}


let changeBackground = () => {
    document.body.style.backgroundSize = "cover";
    return document.body.style.backgroundSize;
}


defInputField.addEventListener("keyup", () => {

    // document.body.style.backgroundSize = "cover";


    setTimeout(userScore, scoreInterval);
    if (splitInputWords.length < 2) {
        correct.style.display = "none";
        incorrect.style.display = "none";
        displayScore.style.display = "none";
    };

    if (totalScore > 5) {
        document.body.style.background = "url('/IMG/moebius3.jpg')";

    };

    if (totalScore > 10) {
        document.body.style.background = "url('/IMG/moebius.jpg')";

    };

    if (userScore() >= 3 || userScore() >= splitDisplayedDef().length) {
        correct.style.display = "block";
        incorrect.style.display = "none"
        displayScore.textContent = userScore();
        displayScore.style.display = "block";


    } else {
        incorrect.style.display = "none";
        correct.style.display = "none";
        displayScore.display ="none";
    }; 

});

defInputField.addEventListener("keydown", (e) => {



    if (e.keyCode === 13 && userScore() >= 1) {
            totalScore += userScore();
            totalScore--;
            currentLevel++;
            newDefButton.textContent = "Definition"
            let newWordObject = newWordObjectGenerator();
            displayNewDef.style.display = "none";
            correct.style.display = "none";
            incorrect.style.display = "none";
            displayScore.style.display = "none";    
            defInputField.value = "";
            displayNewWord.textContent = newWordObject.word;
            displayNewDef.textContent = newWordObject.definition;
            scoreTracker.textContent = "Total Score = " + " " + totalScore;
            levelTracker.textContent = "Level = " + " " + currentLevel;
            console.log(currentLevel);
            console.log(totalScore);

}});

當您調用圖像路徑時,使用backgroundImage而不是background

暫無
暫無

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

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