javascript点击变绿色再点击变红色

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript点击变绿色再点击变红色</title>
</head>
<body>
    <div></div>
    <div></div>
    <div></div>
    <script type="text/javascript">
        var div = document.getElementsByTagName('div')[0];
        div.style.backgroundColor="red";
        div.style.width="50px";
        div.style.height="50px";
        var count = 0;//计数器
        div.onclick=function(){
            count ++;
            if(count % 2 == 1){
                this.style.backgroundColor='green';
            }else{
                this.style.backgroundColor='red'
            }
        }
    </script>
    
</body>
</html>

效果图:

原文地址:https://www.cnblogs.com/huanghuali/p/8433621.html