Home  >  Article  >  Web Front-end  >  How to change the background with javascript

How to change the background with javascript

青灯夜游
青灯夜游Original
2021-06-23 13:58:008531browse

Javascript method to change the background: First use the "document.getElementById('id value')" statement to obtain the specified element object; then use "element object.style.background="background color value or image path"" The statement can set the background.

How to change the background with javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript to change the background

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<style>
	#div{
		height: 200px;
		background: url(img/1.jpg) no-repeat;
	}
</style>
<script>
function displayResult(){
	document.getElementById(&#39;h1&#39;).style.background="paleturquoise";
	document.getElementById(&#39;div&#39;).style.background="url(img/2.jpg) no-repeat";
}
</script>
</head>
<body>

<h1 id="h1" style="background: red;">Hello World!</h1>
<div id="div"></div>
<br>
<button type="button" onclick="displayResult()">改变背景</button>

</body>
</html>

Rendering:

How to change the background with javascript

##Description:

## The #getElementById() method returns a reference to the first object with the specified ID.

    If there is no element with the specified ID, return null
  • If there are multiple elements with the specified ID, return the first one.
  • The background property sets all background properties in one declaration.

The syntax for setting the background attribute:

Object.style.background="color image repeat attachment position"

For more programming-related knowledge, please visit:

Programming Video

! !

The above is the detailed content of How to change the background with javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn