Home > Web Front-end > JS Tutorial > body text

How to change div background color with javascript

醉折花枝作酒筹
Release: 2021-06-15 10:45:14
Original
4948 people have browsed it

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>
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template