Home > Article > Web Front-end > How to change div background color with javascript
In JavaScript, you can use the style object attribute to change the div background color. The syntax format is "element object.style.background="color value"". The Style object represents a single style declaration and can be accessed from the document or element to which the style is applied.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Idea: Clicking on a div changes the background color by judging the number of clicks to change the background color. It mainly uses the addition and accumulation of numbers.
Code;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>js实现点击div改变背景颜色</title> <style> div{ background: red; width: 100px; height: 100px; } </style> </head> <body> <div></div> </body> <script type="text/javascript"> var div=document.getElementsByTagName("div")[0];/*通过标签名div组*/ var count=0;/*计数,从0开始,每点击一下加一*/ div.onclick = function () { /*给div绑定点击函数*/ count ++; /*判断点击的次数,来改变背景颜色*/ if(count % 3==1){ this.style.background="yellow" }else if(count % 3==0){ this.style.background="red" }else { this.style.backgroundColor="#ff9000" } } </script> </html>
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to change div background color with javascript. For more information, please follow other related articles on the PHP Chinese website!