js 跳躍的小球案例

<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>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容