iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
0
自我挑戰組

大器可以晚成—— 30歲才開始的轉職工程師之路系列 第 27

[ Day 27 | JS ] 用 mousemove 來做個小遊戲

ㄖ在之前的文章中有提到,設置監聽器時有許多事件可以設定,例如 "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('挑戰失敗!!');
  });
};

完成!

閃避小遊戲

fail

來這邊玩玩看 :)


上一篇
[ Day 26 | JS ] keydown 事件
下一篇
[ Day 28 | JS ] ESLint 讓你的程式碼符合規範
系列文
大器可以晚成—— 30歲才開始的轉職工程師之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言