The backgroundImage
property sets or gets
the background image of an element.
backgroundImage |
Yes | Yes | Yes | Yes | Yes |
Return the backgroundImage property:
var v = object.style.backgroundImage
Set the backgroundImage property:
object.style.backgroundImage=url('URL')|none|initial|inherit
Default Value: | none |
---|---|
Return Value: | A string representing the background image |
CSS Version | CSS1 |
The following code shows how to set a background image for a document.
<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!-- www.ja v a2 s .c o m-->
document.body.style.backgroundColor = "#f3f3f3";
document.body.style.backgroundImage = "url('http://java2s.com/style/demo/border.png')";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to set a background image of a specific <div> element.
<!DOCTYPE html>
<html>
<head>
<style>
div {<!-- ww w . ja v a 2s . co m-->
width: 400px;
height: 400px;
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<div id="myDiv">This is a div element.</div>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
document.getElementById("myDiv").style.backgroundImage = "url('http://java2s.com/style/demo/border.png')";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to get the background image of a specific <div> element.
<!DOCTYPE html>
<html>
<body>
<!-- w ww .j a v a 2 s .c om-->
<h1>Hello World!</h1>
<div id="myDiv" style="background-image:url('http://java2s.com/style/demo/border.png');border:1px solid black;height:400px;width:400px;">This is a div element.</div>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
alert(document.getElementById("myDiv").style.backgroundImage);
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to get the background image of a document.
<!DOCTYPE html>
<html>
<body style="background:#f3f3f3 url('http://java2s.com/style/demo/border.png');">
<!--from w w w. j a va 2 s. c om-->
<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
console.log(document.body.style.backgroundImage);
}
</script>
</body>
</html>
The code above is rendered as follows: