DOM七十二变练习
2022-06-07
<!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>
        html.body {
            height: 100%;
            width: 100%;
            overflow: hidden;
        }
       /* #msg{
           height: 100px;
           display: block;           未设置高度,所以按钮会跟随字体跳动,随着字体的大小而被撑开所以很难点击
       } */
       #stop{
           position: absolute;
           left: 50%;                     也可以加绝对定位解决 脱离文档流
           top: 50%;
       }
    </style>
</head>
<body>
    <span id="msg">看我72变</span>
    <br>
    <br><br><br><br><br><br><br><br>
    <button id="open">开始</button>
    <button id="stop">停止</button>
    <script>
        //页面加载,随机生成颜色,和设置字体大小
        //并且字体随机变大五次后变小
        var oOpen = document.getElementById("open");
        var oStop = document.getElementById("stop");
        //1.随机颜色
        function randomColor1() {
            var str = "#";
            for (var i = 0; i < 6; i++) {
                str += parseInt(Math.random() * 16).toString(16)
            }
            return str;
        }
        //2.随机颜色的第二种写法  rgb(255,255,255)
        function randomColor2() {
            var str = "rgb("
            str += parseInt(Math.random() * 256) + ",";
            str += parseInt(Math.random() * 256) + ","
            str += parseInt(Math.random() * 256) + ","
            return str;
        }
        // 3
        var oMsg = document.querySelector("#msg");
        var n = 0;
        oOpen.onclick = function () {
            clearInterval(timer)
            timer = setInterval(function () {
                document.body.style.backgroundColor = randomColor1();
                oMsg.style.color = randomColor2();
                n++;
                if (Math.abs(n) >= 6) {
                    n *= -1
                }
                oMsg.style.fontSize = 16 + Math.abs(n) * 5 + "px";
            }, 500);
        }
        var timer
        oStop.onclick = function () {
            clearInterval(timer)
        }
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号