美文网首页
按钮使用随件颜色

按钮使用随件颜色

作者: 心存美好 | 来源:发表于2022-03-08 09:08 被阅读0次

    按钮使用随件颜色

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            body {
                font-family: "Microsoft YaHei", serif;
                user-select: none
            }
    
            body,
            dl,
            dd,
            p,
            h1,
            h2,
            h3,
            h4,
            h5,
            h6 {
                margin: 0;
            }
    
            ol,
            ul,
            li {
                margin: 0;
                padding: 0;
                list-style: none;
            }
    
            img {
                border: none;
            }
    
            #button {
                width: 100px;
                height: 35px;
                line-height: 35px;
                cursor: pointer;
                text-align: center;
                font-size: 14px;
                border: 1px solid #ffd9ae;
            }
    
            #button.pink {
                background-color: pink;
                color: white;
    
            }
    
            #button.blue {
                background-color: blue;
                color: #AAA;
            }
    
            #button.red {
                background-color: red;
                color: #ffd9ae
            }
    
            #button.orange {
                background-color: orange;
                color: #f1f1f1;
            }
        </style>
    </head>
    
    <body>
        <div id="button" class="pink">按钮</div>
    
        <script>
            //按钮切换多个背景颜色
            //1、获取元素
            let oBtn = document.getElementById('button')
            //2、罗列一个数组 放背景颜色
            let bgArr = ['pink', 'blue', 'red', 'orange']
            let i = 0;//定义索引
            // let len = bgArr.length;
            //3、绑定事件
            oBtn.onclick = function () {
                // this.style.backgroundColor = '#'+Math.random().toString(16).substr(2,6);//使用随机函数获得随机数,随机颜色
                // i++
                // if (i >= len) {
                //     i = 0
                // }
                i = ++i % 4;
                console.log(bgArr[i]);
                this.className = bgArr[i]//循环改变背景颜色
            }
        </script>
    </body>
    
    </html>
    

    相关文章

      网友评论

          本文标题:按钮使用随件颜色

          本文链接:https://www.haomeiwen.com/subject/oetarrtx.html