<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">點(diǎn)擊小球開始運(yùn)動</button>
? ? <button @click="end">點(diǎn)擊小球停止運(yùn)動</button>
? </div>
</template>
<script>
export default {
? //小球運(yùn)動知識點(diǎn)梳理 ?核心思路是利用定位改變top left值來移動
? data() {
? ? return {
? ? ? // 定義小球xy的坐標(biāo)變量
? ? ? ballX: 0,
? ? ? ballY: 0,
? ? ? // 定義小球xy移動的距離變量
? ? ? yidongx: 1,
? ? ? yidongy: 1,
? ? ? kongzhi: "",
? ? };
? },
? methods: {
? ? // 封裝一個運(yùn)動的函數(shù)
? ? yundong() {
? ? ? // 讓小球移動 小球x坐標(biāo) = 小球x坐標(biāo)+距離*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);
? ? ? // 判斷小球移動距離是否超過了外層盒子大小 小球坐標(biāo)加上小球距離左邊的寬度如果大于了外邊的盒子 或者 坐標(biāo)小于0 e讓移動距離等于負(fù)值 反方向運(yùn)動
? ? ? 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;
? ? ? // 需要不停調(diào)用函數(shù) 加定時器 setinterval 還需要停止 所以需要一個變量接收
? ? ? that.kongzhi = setInterval(function () {
? ? ? ? that.yundong();
? ? ? }, 10);
? ? },
? ? end() {
? ? ? clearInterval(this.kongzhi);
? ? },
? },
};
</script>
<style>
button {
? position: absolute;
? bottom: 0;
? right: 0;
}
</style>