iT邦幫忙

2025 iThome 鐵人賽

DAY 9
0

實作一:隨滑鼠移動的小球

  • 今天將會嘗試撰寫一段簡單的範例應用,在頁面上繪製一塊區域,在區域內繪製一個圓形球體,我們需要實現當滑鼠在區域內移動時,球體可以平滑地隨滑鼠移動。而要實現的辦法就是需要監聽滑鼠的移動事件,並且做好元素座標的更新即可。
  • 首先建立一個名為ball.html的檔案,可以將頁面的HTML版面設定撰寫出來,要實現這樣的範例應用,只需要兩個內容元素即可。
<!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8">
  <title>Ball Move</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <style>
    body {
        margin: 0;
        padding: 0;
    }
    .container {
        margin: 0;
        padding: 0;
        position: absolute;
        width: 440px;
        height: 440px;
        background-color: blanchedalmond;
        display: inline;
    }
    .ball {
        position: absolute;
        width: 60px;
        height: 60px;
        left: 100px;
        top: 100px;
        background-color: red;
        border-radius: 30px;
        z-index: 100;
    }
  </style>
</head>
<body>
  <div id="Application">
    <div class="container" @mousemove.stop="move">
      <div class="ball" :style="{ left: offsetX + 'px', top: offsetY + 'px' }"></div>
    </div>
  </div>
  <script>
    const App = {
      data() {
        return {
          offsetX: 0, // 小球的水平座標
          offsetY: 0  // 小球的垂直座標
        }
      },
      methods: {
        move(event) {
          // 視窗長寬 440,小球半徑 30
          // 檢查右側不能超出邊界
          if (event.clientX + 30 > 440) {
            this.offsetX = 440 - 60
          }
          // 檢查左側不能超出邊界
          else if (event.clientX - 30 < 0) {
            this.offsetX = 0
          } else {
            this.offsetX = event.clientX - 30
          }

          // 檢查下側不能超出邊界
          if (event.clientY + 30 > 440) {
            this.offsetY = 440 - 60
          }
          // 檢查上側不能超出邊界
          else if (event.clientY - 30 < 0) {
            this.offsetY = 0
          } else {
            this.offsetY = event.clientY - 30
          }
        }
      }
    }
    Vue.createApp(App).mount("#Application")
  </script>
</body>
</html>
  • 執行後會得到結果如下,因無法放影片上來,以截圖顯示小球跟隨滑鼠改變位置。
    https://ithelp.ithome.com.tw/upload/images/20250923/20169282Idy9g62mTs.png
    https://ithelp.ithome.com.tw/upload/images/20250923/20169282vGeZj7T3sh.png
    https://ithelp.ithome.com.tw/upload/images/20250923/20169282m0sBzTCWmV.png
    https://ithelp.ithome.com.tw/upload/images/20250923/20169282RtMVd7qZCd.png
  • 可以看到小球位置分別出現在四個不同角落。

今天就先到這邊,明天會稍微對這段程式做一些調整。


上一篇
Day 8
下一篇
Day 10
系列文
從零開始學習TypeScript、Vue.js !!10
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言