<template>
<div
ref="waiceng"
style="
width: 500px;
height: 400px;
background-color: pink;
border: 1px solid #ccc;
margin: 0 auto;
position: relative;
"
>
<div
class="qiu"
ref="huoQuDom"
style="
width: 16px;
height: 16px;
background-color: black;
position: absolute;
left: 0;
top: 0;
border-radius: 50%;
"
></div>
<button style="right: 150px" @click="kaishi">点击小球开始运动</button>
<button @click="end">点击小球停止运动</button>
</div>
</template>
<script>
export default {
//小球运动知识点梳理 核心思路是利用定位改变top left值来移动
data() {
return {
// 定义小球xy的坐标变量
ballX: 0,
ballY: 0,
// 定义小球xy移动的距离变量
yidongx: 1,
yidongy: 1,
kongzhi: "",
};
},
methods: {
// 封装一个运动的函数
yundong() {
// 让小球移动 小球x坐标 = 小球x坐标+距离*2
this.ballX = this.ballX + this.yidongx * 2;
this.ballY = this.ballY + this.yidongy * 2;
// 给小球赋值 vue采用$refs.name.style来变更样式
this.$refs.huoQuDom.style.left = this.ballX + "px";
this.$refs.huoQuDom.style.top = this.ballY + "px";
console.log(this.$refs.huoQuDom.style.left);
console.log(this.$refs.huoQuDom.style.top);
console.log(this.$refs.huoQuDom.offsetWidth);
// 判断小球移动距离是否超过了外层盒子大小 小球坐标加上小球距离左边的宽度如果大于了外边的盒子 或者 坐标小于0 e让移动距离等于负值 反方向运动
if (
this.ballX + this.$refs.huoQuDom.offsetWidth >
this.$refs.waiceng.offsetWidth ||
this.ballX < 0
) {
this.yidongx = -this.yidongx;
}
if (
this.ballY + this.$refs.huoQuDom.offsetHeight >
this.$refs.waiceng.offsetHeight ||
this.ballY < 0
) {
this.yidongy = -this.yidongy;
}
},
kaishi() {
var that = this;
// 需要不停调用函数 加定时器 setinterval 还需要停止 所以需要一个变量接收
that.kongzhi = setInterval(function () {
that.yundong();
}, 10);
},
end() {
clearInterval(this.kongzhi);
},
},
};
</script>
<style>
button {
position: absolute;
bottom: 0;
right: 0;
}
</style>