javascript如何改变div背景颜色


本文摘自PHP中文网,作者醉折花枝作酒筹,侵删。

在javascript中,可以使用style对象属性改变div背景颜色,语法格式为“元素对象.style.background="颜色值"”。Style对象代表一个单独的样式声明,可从应用样式的文档或元素访问Style对象。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

思路:点击div改变背景颜色,是通过判断点击的次数,达到改变背景颜色,主要运用了数的加,累加。

代码;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

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

【推荐学习:javascript高级教程

以上就是javascript如何改变div背景颜色的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

javascript如何改变div背景颜色

更多相关阅读请进入《div点击改变背景色》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...