js+html簡單計時器
阿新 • • 發佈:2021-12-24
咱們話不多說!整活
第一步:建立html表單
<div class="body"> <div class="text"> Counter </div> <div class="count" > <span id="demo" class="ft">0 </span> </div> <div class="btn"> <button type="button" onclick="add()"class="btn1">+</button> <button type="button" onclick="zero()" class="btn2">零</button> <button type="button" onclick="sub()" class="btn1">-</button> <button type="button" onclick="stop()" class="btn2">||</button> </div> </div>
第二步:加入css樣式使其看起來比較美觀
<style> .body { width: 300px; height: 500px; background-image: linear-gradient(rgb(11, 142, 229),white);//顏色漸變 border-radius: 20px;//圓角邊框 display: flex;彈性盒子 flex-direction: column; align-items: center; margin: 0 auto;居中 } .text { font-size: 24px; color: white; margin-top: 60px; text-shadow: 2px 2px 2px #fff;//陰影 } .count { position: relative; width: 200px; height: 200px; margin-top: 60px; border-color: rgb(11, 142, 229); border-radius: 50%; display: flex; } .ft { font-size: 100px; color: #fff; margin: auto; } .btn { width: 220px; display: flex; justify-content: space-between;//彈性佈局:均勻分佈 margin-top: 60px; } .btn1 { width: 50px; height: 30px; border: 0px; border-radius: 4px; background-color: rgb(11, 142, 229); font-size: 20px; color: #efdaff; } .btn2 { width: 50px; height: 30px; border: 0px; border-radius: 4px; background-color:rgb(11, 142, 229); font-size: 22px; color: #efdaff; } </style>
第三步:加入js,使其動起來
var counter = document.getElementById("demo").innerHTML;//定義一個變數counter function add() {//點選函式,當點選+號時,開始計數 counter++;//counter自加 document.getElementById("demo").innerHTML = counter+'s'; counter=setTimeout(add,1000)//每間隔1000毫秒執行一次add函式 } function sub() {//點選減號,函式執行 if(counter == 0) {//如果counter等於0;counter=0; counter = 0; } else {如果counter不等於0;counter數值-1 counter--; document.getElementById("demo").innerHTML = counter+'s'; } } function zero() {//點選零,記數歸零 counter = 0; document.getElementById("demo").innerHTML = counter; } function stop() {//點選||,停止計數 clearInterval(counter) } </script>
大體效果就是這樣的:
問題:1.連續點選+號會造成資料重新整理過快,也就是倍速計數,但是通過點選-號會減低倍速
2.點選||號可停止計數,點選加號可開始計數;
如果後期發現問題,可聯絡小白及時改正;