1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- .box {
- width: 300px;
- height: 300px;
- background-color: #fff;
- box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
- border-radius: 10px;
- position: fixed;
- top: 50%;
- left: 50%;
- margin-left: -150px;
- margin-top: -150px;
- text-align: center;
- }
- .box .num {
- font-size: 50px;
- font-weight: bold;
- color: #333;
- }
- .box button {
- width: 100px;
- height: 50px;
- border: 1px solid black;
- border-radius: 5px;
- font-size: 25px;
- }
- </style>
- </head>
- <body>
- <div class="box">
- <p class="num">10</p>
- <button>开始</button>
- </div>
- <script>
- // 第一步获取元素
- // 获取按钮
- var oBtn = document.getElementsByTagName("button");
- // 把数组中的标签取出来
- oBtn = oBtn[0];
- // 获取数字标签
- var numEle = document.getElementsByClassName("num");
- // 把数组中的标签取出来
- numEle = numEle[0];
- // console.log(oBtn);
- // console.log(numEle);
- // 第二步绑定事件
- // 准备一个变量用来装递减的数字
- var num = 10;
- var timer = null;
- // 每次促发事件生成的事件处理函数不是同一个
- oBtn.onclick = function () {
- // 判断开始或结束
- // 获取按钮中的文字,根据文字判断开始或结束
- var btnText = oBtn.innerText;
- if (btnText == "开始") {
- oBtn.innerText = "暂停";
- // 第三步开始倒计时
- timer = setInterval(function () {
- //让数字开始递减
- num--;
- // 把递减之后的数字放到页面里
- numEle.innerText = num;
- }, 1000);
- } else {
- oBtn.innerText = "开始";
- // 清除定时器
- clearInterval(timer);
- }
- }
- </script>
- </body>
- </html>
|