<!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>
今天就先到這邊,明天會稍微對這段程式做一些調整。