如何使用javascript更改div的背景图像?

sha*_*b0o 16 html javascript css

这是我的代码

        <div style="text-align:center;">
            <div class="ghor" id="a" onclick="chek_mark()">
            </div>
Run Code Online (Sandbox Code Playgroud)

功能调用

        <script type="text/javascript">

            function chek_mark(){
                var el= document.getElementById("a").style.background-    image;
Run Code Online (Sandbox Code Playgroud)

在这里,我想使用if else条件更改背景图像

if (el.url("Black-Wallpaper.jpg"))  
                    {                                  
                        el.url = "cross1.png";  
                    }
                    else if(el.url("cross1.png"))
                    {

                      alert("<h1>This is working too.</h1>");
                    }
                }
Run Code Online (Sandbox Code Playgroud)

这是样式表

.ghor //this is the div class
{
    background-image: url('Black-Wallpaper.jpg');
    background-size: cover;
    border-radius: 5px;
    height: 100px;
    width: 100px;
    box-shadow: 2px 5px 7px 7px white;
    /*background-color: black;*/
    display:inline-block; 
}
Run Code Online (Sandbox Code Playgroud)

我想改变'div'的背景图片,这个类是'ghor'

imm*_*odi 33

试试这个:

document.getElementById('a').style.backgroundImage="url(images/img.jpg)"; // specify the image path here
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


Afz*_*han 5

试试这个!

var el = document.getElementById("a").style.backgroundImage;
if(el == "url(Black-Wallpaper.jpg)") { // full value is provided
   el.style.backgroundImage = "url(/link/to_new_file.png)"; // change it
}
Run Code Online (Sandbox Code Playgroud)