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.
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('h1').style.background="paleturquoise"; document.getElementById('div').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:
## The #getElementById() method returns a reference to the first object with the specified ID.
The syntax for setting the background attribute:
Object.style.background="color image repeat attachment position"
For more programming-related knowledge, please visit:
Programming VideoThe 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!