如何检查使用纯JS显示的背景图像

时间:2018-12-20 07:45:38

标签: javascript html css

我基本上想根据显示的背景图像使用if / else语句。

document.getElementById('background').style.background="url(assets/img/silhouette_5.jpg)"

if(document.getElementById('background').style.backgroundImage=="url(assets/img/silhouette_5.jpg)")
{
    alert("kek")
}else{
    alert(":(")
}
}

我尝试同时使用style.background和style.backgroundImage,但无法正常工作。无论我做什么,我都会收到“ :(”警报

预先感谢

2 个答案:

答案 0 :(得分:3)

您只是错过了<img src="https://i.imgur.com/YWNyGHD.png" usemap="#mymap" /> <map name="mymap"> <area shape = “poly” coords = “370, 66, 395, 72, 406, 74, 414, 76, 425, 89, 441, 106, 461, 105, 462, 117, 460, 124, 465, 138, 461, 152, 449, 168, 453, 174, 444, 182, 425, 183, 419, 176, 397, 181, 397, 196, 401, 202, 384, 224, 374, 214, 368, 196, 356, 196, 373, 156, 360, 148, 334, 156, 350, 145, 356, 133, 347, 125, 346, 103, 355, 93, 385, 103, 380, 90, 385, 79 379, 72, 369, 73, 370, 66 ” href = “#” title = “khorasan”/> </map>内的""

设置url("...")时,代码将生成为url(...)

如果您打印背景,则可以找到它:

url("...")

这是工作代码

console.log(document.getElementById('background').style.background)
document.getElementById('background').style.background="url(assets/img/silhouette_5.jpg)"

if(document.getElementById('background').style.background=='url("assets/img/silhouette_5.jpg")')
{
    alert("kek")
}else{
   alert(":(")
}

答案 1 :(得分:0)

这很好用:

document.getElementById('background').setAttribute ("style","background: url(Images/background1.jpg)");
if(document.getElementById('background').getAttribute("style") == "background: url(Images/background1.jpg)") {
    alert("kek")
} else {
    alert(":(")
}

<div id="background"></div>