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

How to change div background color with javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-11 17:18:214954browse

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.

How to change div background color with javascript

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!

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