这是我的代码
<div style="text-align:center;">
<div class="ghor" id="a" onclick="chek_mark()">
</div>
函数调用
<script type="text/javascript">
function chek_mark(){
var el= document.getElementById("a").style.background- image;
这里我想使用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>");
}
}
这是样式表
.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;
}
我想要改变'div'的背景图像,该类是'ghor'
答案 0 :(得分:30)
试试这个:
document.getElementById('a').style.backgroundImage="url(images/img.jpg)"; // specify the image path here
希望它有所帮助!
答案 1 :(得分:4)
尝试这个!
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
}
答案 2 :(得分:2)
您可以通过以下方式实现
第1步
var imageUrl= "URL OF THE IMAGE HERE";
var BackgroundColor="RED"; // what ever color you want
用于更改 BODY
的背景document.body.style.backgroundImage=imageUrl //changing bg image
document.body.style.backgroundColor=BackgroundColor //changing bg color
更改ID
的元素document.getElementById("ElementId").style.backgroundImage=imageUrl
document.getElementById("ElementId").style.backgroundColor=BackgroundColor
适用于具有相同类别的元素
var elements = document.getElementsByClassName("ClassName")
for (var i = 0; i < elements.length; i++) {
elements[i].style.background=imageUrl;
}
答案 3 :(得分:0)
<body id="body">
</body>
您还可以设置时间。
//Initializing
var i = 0;
var images = []; //array
var time = 3000; // time in millie seconds
//images
images[0] = "url(./Images/1.jpg)";
images[1] = "url(./Images/2.jpg)";
images[2] = "url(./Images/3.jpg)";
//function
function changeImage() {
var el = document.getElementById('body');
el.style.backgroundImage = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout('changeImage()', time);
}
window.onload = changeImage;
overflow-x: hidden;
margin: 0;
padding: 0;
width: 100%;
height: 100vh;
background-repeat: no-repeat;
background-position: center;
答案 4 :(得分:0)
target_include_directories()