<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>點擊變色小球</title>
<script src="https://unpkg.com/vue@3"></script>
<style>
body { /* 重置頁面邊距 */
margin: 0;
padding: 0;
}
.container { /* 容器樣式 - 小球的活動範圍 */
margin: 0;
padding: 0;
position: absolute;
width: 440px;
height: 440px;
background-color: blanchedalmond;
display: inline;
border: 2px solid #333; /* 讓邊界更明顯 */
cursor: pointer; /* 滑鼠移到容器上會變成小手指 */
}
.ball { /* 小球樣式 */
position: absolute;
width: 60px;
height: 60px;
border-radius: 30px; /* 讓方形變成圓形 */
z-index: 100; /* 確保在最上層 */
transition: background-color 0.3s ease; /* 顏色變化的平滑過渡效果 */
}
.info { /* 資訊顯示區域 */
position: absolute;
top: 450px; /* 放在容器下方 */
left: 0;
font-family: Arial, sans-serif;
font-size: 14px;
}
</style>
</head>
<body>
<div id="Application">
<div class="container" @mousemove.stop="move" @click="changeColor">
<div class="ball" :style="{left: offsetX+'px', top: offsetY+'px', backgroundColor: colors[colorIndex]}"></div>
</div>
<!-- 資訊顯示區域 -->
<div class="info">
<p>🎨 移動滑鼠控制小球,點擊容器變色!</p>
<p>目前顏色: {{ colorNames[colorIndex] }} | 點擊次數: {{ clickCount }}</p>
</div>
</div>
<script>
const App = {
data() {
return {
offsetX: 0,
offsetY: 0,
colors: ['red', 'blue', 'green', 'orange', 'purple'], // 顏色陣列
colorNames: ['紅色', '藍色', '綠色', '橙色', '紫色'], // 中文顏色名稱
colorIndex: 0, // 目前顏色的索引
clickCount: 0 // 點擊次數計數器
}
},
methods: {
move(event) { // 獲取容器的邊界資訊
const container = event.currentTarget;
const rect = container.getBoundingClientRect();
const relativeX = event.clientX - rect.left; // 計算滑鼠相對於容器的座標
const relativeY = event.clientY - rect.top;
if (relativeX + 30 > 440) { // X軸邊界檢查(小球半徑為30px)
this.offsetX = 440 - 60; // 右邊界限制
} else if (relativeX - 30 < 0) {
this.offsetX = 0; // 左邊界限制
} else {
this.offsetX = relativeX - 30; // 正常跟隨
}
if (relativeY + 30 > 440) { // Y軸邊界檢查
this.offsetY = 440 - 60; // 下邊界限制
} else if (relativeY - 30 < 0) {
this.offsetY = 0; // 上邊界限制
} else {
this.offsetY = relativeY - 30; // 正常跟隨
}
},
changeColor() { // 處理顏色變換
this.colorIndex = (this.colorIndex + 1) % this.colors.length;
this.clickCount++; // 增加點擊計數
}
}
}
Vue.createApp(App).mount('#Application');
</script>
</body>
</html>
今天就先這樣囉,明天將會進行第二個實作練習!