ㄖ在之前的文章中有提到,設置監聽器時有許多事件可以設定,例如 "click"等。
今天我們就用另一個事件 "mousemove" 來實作個簡易小遊戲吧!
首先寫好簡單的 HTML:
<body>
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
<div class="box box5"></div>
<div class="box box6"></div>
</body>
和套上 animation 的 CSS:
.box {
background-color: #66036a;
width: 20px;
height: 20px;
position: absolute;
}
.box1 {
top: 50px;
left: 50px;
animation: fontbulger 2s infinite;
}
.box2 {
top: 50px;
left: 100px;
animation: fontbulger 1s infinite;
}
.box3 {
top: 50px;
left: 150px;
animation: fontbulger 2.5s infinite;
}
.box4 {
top: 50px;
left: 200px;
animation: fontbulger .7s infinite;
}
.box5 {
top: 50px;
left: 250px;
animation: fontbulger 1.7s infinite;
}
.box6 {
top: 50px;
left: 300px;
animation: fontbulger .9s infinite;
}
@keyframes fontbulger {
0%: {
top: 0px;
}
50% {
top: 200px;
width: 25px;
height: 50px;
background-color: #f3c500;
}
100%: {
top: 0px;
}
}
最後加上監聽器:
let boxs = document.querySelectorAll('.box');
//回傳的資料會是陣列
for(i = 0; i < boxs.length; i++) {
boxs[i].addEventListener('mousemove', () => {
alert('挑戰失敗!!');
});
};
來這邊玩玩看 :)