<!DOCTYPE html>
<html>
<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>小游戲</title>
? ? <style>
? ? ? ? *{
? ? ? ? ? ? margin: 0;
? ? ? ? ? ? padding: 0;
? ? ? ? }
? ? ? ? .dian{
? ? ? ? ? ? width: 30px;
? ? ? ? ? ? height: 30px;
? ? ? ? ? ? background-color: red;
? ? ? ? ? ? position: absolute;
? ? ? ? }
? ? ? ? .num{
? ? ? ? ? ? font-size: 20px;
? ? ? ? }
? ? </style>
</head>
<body>
? ? <div class="num">
? ? ? ? <span>當(dāng)前數(shù)量:</span>
? ? ? ? <span id="num"></span>
? ? </div>
? ? <script>
? ? ? ? // window.innerWidth 返回視口寬度
? ? ? ? // console.log(window.innerWidth);
? ? ? ? // window.innerHeight 返回視口高度
? ? ? ? // console.log(window.innerHeight);
? ? ? ? // 生成元素的最大left值
? ? ? ? let maxLeft = window.innerWidth - 30
? ? ? ? // 生成元素的最大top值
? ? ? ? let maxTop = window.innerHeight - 30
? ? ? ? //該定時(shí)器生成點(diǎn)
? ? ? ? //定時(shí)器有一個(gè)返回值
? ? ? ? let timer1 = setInterval(() => {
? ? ? ? ? ? // 創(chuàng)建一個(gè)div元素
? ? ? ? ? ? let dian = document.createElement('div')
? ? ? ? ? ? // 個(gè)創(chuàng)建的div元素添加類選擇器樣式
? ? ? ? ? ? dian.className = 'dian'
? ? ? ? ? ? dian.style.left = Math.random()*maxLeft+'px'
? ? ? ? ? ? dian.style.top = Math.random()*maxTop+'px'
? ? ? ? ? ? // 每個(gè)元素注冊(cè)點(diǎn)擊事件
? ? ? ? ? ? dian.onclick = function(){
? ? ? ? ? ? ? ? this.remove()
? ? ? ? ? ? }
? ? ? ? ? ? // 將創(chuàng)建的div元素添加到body中
? ? ? ? ? ? document.body.appendChild(dian)
? ? ? ? }, 500);
? ? ? ? console.log(timer1);
? ? ? ? //該定時(shí)器統(tǒng)計(jì)點(diǎn)的數(shù)量,并判斷游戲是否結(jié)束
? ? ? ? let timer2 = setInterval(() => {
? ? ? ? ? ? //獲取數(shù)量
? ? ? ? ? ? let num = document.querySelectorAll('.dian').length
? ? ? ? ? ? //顯示當(dāng)前點(diǎn)的數(shù)量
? ? ? ? ? ? document.querySelector('#num').innerHTML = num
? ? ? ? ? ? //判斷游戲是否結(jié)束
? ? ? ? ? ? if(num>=10){
? ? ? ? ? ? ? ? alert('Game Over~~')
? ? ? ? ? ? ? ? // 清除定時(shí)器
? ? ? ? ? ? ? ? clearInterval(timer1)
? ? ? ? ? ? ? ? clearInterval(timer2)
? ? ? ? ? ? }
? ? ? ? }, 100);
? ? </script>
</body>
</html>