遊戲按鈕
原生js實現遊戲的‘開始’‘暫停’‘結束’
實現:
使用setInterval實現
js實現步驟:
- 獲取元素
- 開始事件
- 停止事件
- 暫停事件
- 定時器
效果演示:
html代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>按鈕</title>
<style>
.wrap{
width: 30%;
margin: 200px auto;
padding: 30px;
box-shadow: 0 0 20px #999;
border-radius: 10px;
}
input{
padding: 10px 15px;
margin-right: 10px;
}
.btnGroup button{
display: inline-block;
padding: 10px 25px;
background: #00A09D;
border-radius: 5px;
color: white;
margin-right: 10px;
outline: none;
border: none;
}
/*動畫樣式*/
.btnGroup button:hover {
animation: shake .5s;
}
@keyframes shake {
0% {
transform: rotate(0deg);
}
25% {
transform: rotate(5deg);
}
50% {
transform: rotate(-10deg);
}
75% {
transform: rotate(5deg);
}
100% {
transform: rotate(0);
}
}
</style>
</head>
<body>
<div class="wrap">
<input type="text" placeholder="輸入遊戲總時長">分鐘
<p>倒計時:<span class="endTime"></span>秒</p>
<div class="btnGroup">
<button class="start">開始</button>
<button class="pause">暫停</button>
<button class="stop">結束</button>
</div>
</div>
</body>
</html>
有加入一丟丟c3的動畫
js代碼
window.onload = function(){
// 1.獲取元素
var endTimeStr = document.getElementsByClassName('endTime')[0];
var timeVal = document.getElementsByTagName('input')[0];
var startBtn = document.getElementsByClassName('start')[0];
var pauseBtn = document.getElementsByClassName('pause')[0];
var stopBtn = document.getElementsByClassName('stop')[0];
var totalTime, //總時長
showTime,//剩餘時長
startTime, //點開始按鈕時間戳
nowTime,//定時器開啓的時間戳
timer;
var timeType = 1; //1結束後開始 2暫停後開始
// 2.開始事件
startBtn.onclick = function(){
if(timer) clearInterval(timer);
if(timeType==1)totalTime = timeVal.value*60; //初始化總時長
startTime = new Date(); //點擊按鈕開始時間
startBtn.disabled = true;
start();
}
// 3.停止事件
stopBtn.onclick = function(){
clearInterval(timer)
timeType = 1;
showTime = timeVal.value*60; //剩餘時長
endTimeStr.innerHTML = showTime;
startBtn.disabled = false;
}
// 4.暫停事件
pauseBtn.onclick = function(){
clearInterval(timer)
timeType = 2;
startBtn.disabled = false;
totalTime = showTime; //總時長==剩餘時長
}
/*
定時器
*/
function start(){
nowTime = new Date();//定時器開始時間
showTime = totalTime-parseInt((nowTime-startTime)/1000);
endTimeStr.innerHTML = showTime;
timer = setInterval(function(){
showTime--;
endTimeStr.innerHTML = showTime;
if(showTime<1){
clearInterval(timer)
alert("遊戲結束");
}
},100);
}
}
代碼複製可直接查看效果