简体   繁体   English

发生特定事件后,如何让 div 更改其背景图像?

[英]How can I get a div to change its background-image after a specific event has taken place?

I have made a game using JavaScript and I would like the background to change after the game is over or after isGamerOver = true to be more specific.我使用 JavaScript 制作了一个游戏,我希望在游戏结束后或 isGamerOver = true 之后改变背景更具体。 Here is what I currently have.这是我目前拥有的。 Right now when ever the game ends I get a Uncaught TypeError: Cannot read property 'style' of null.现在,当游戏结束时,我得到一个 Uncaught TypeError: Cannot read property 'style' of null。

function gameOver() {
    console.log('game over')
    isGamerOver = true
    while (grid.firstChild) {
        grid.removeChild(grid.firstChild)
    }
    grid.innerHTML = score
   
    clearInterval(upTimerId)
    clearInterval(downTimerId)
    clearInterval(leftTimerId)
    clearInterval(rightTimerId)
   
    if(isGamerOver = true){
    document.getElementById("grid").style.backgroundImage="url('backgrounds/background-up.png')";
    }else{
    document.getElementById("grid").style.backgroundImage="url('backgrounds/game-over.png')";
    }
}

Here is the style sheet I am trying to change这是我要更改的样式表

.grid  {
width: 400px;
height: 600px;
background-image: url(backgrounds/background-up.png);  
position: relative;
font-size: 100px;
text-align: center;
color: #fff;
}

Here Is my HTML这是我的 HTML

<!DOCTYPE html>
    <html lang="en"  dir="ltr">
    <head>
        <meta charset="UTF-8">
        <title>100% Not Doodle Jump</title>
        <link rel="stylesheet" href="style.css"></link>
        <script src="app.js" charset="utf-8"></script>
    </head>
    <body>
    
        <div class="grid"></div>
    
    </body>
 </html>

I also added a div in JavaScript我还在 JavaScript 中添加了一个 div

const grid = document.querySelector('.grid')
const doodler = document.createElement('div')

If you got your grid defined like that:如果你的网格是这样定义的:

const grid = document.querySelector('.grid')

change this:改变这个:

if(isGamerOver = true){
   document.getElementById("grid").style.backgroundImage="url('backgrounds/background-up.png')";
}else{
   document.getElementById("grid").style.backgroundImage="url('backgrounds/game-over.png')";
}

to this:对此:

if(isGamerOver = true){
   grid.style.backgroundImage="url('backgrounds/background-up.png')";
}else{
   grid.style.backgroundImage="url('backgrounds/game-over.png')";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM