点击有惊喜案例

编辑本博客

  • 通过getElementsByClassName获取元素
  • 通过this.style.background="red"来为元素设置样式
  • 通过this.innerText来获取元素中文本内容或设置文本内容
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>点击惊喜案例</title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        .box{
            width: 100px;
            height: 100px;
            background-color: red;
            text-align: center;
            margin: 50px auto;
            line-height: 100px;
        }
    </style>
</head>
<body>
    <div class="box">点击有惊喜</div>
</body>
<script type="text/javascript">
    var oDiv=document.getElementsByClassName("box")[0]
    i=0
    oDiv.onclick=function () {
        i++;
        if(i%4==1){
            this.style.backgroundColor="yellow";
            this.innerText="继续点";
        }else if(i%4==2){
            this.style.backgroundColor="black";
            this.style.color="white";
            this.innerText="哈哈";
        }
        else if(i%4==3){
            this.style.backgroundColor="green";
            this.style.color="white";
            this.style.fontWeight="bold";
            this.innerText="哈哈";
        }
        else{
            this.style.backgroundColor="red";
            this.style.color="black";
            // this.style.fontWeight="bold";
            this.innerText="回去了";
        }
    }
</script>
</html>
View Code

原文地址:https://www.cnblogs.com/yaya625202/p/9189726.html