首先,将小球儿动画代码封装成组件,创建个文件,例如qiu.js
let createBall = (left, top,box) => {// 点击事件 const {clientX,clienty} = ev createBall(clientX,clienty)const ball = document.createElement('div');ball.style.position = 'absolute';ball.style.left = left - 2+ 'px';ball.style.top = top - 5 + 'px';ball.style.width = '10px';ball.style.height = '10px';ball.style.borderRadius = '50%';ball.style.backgroundColor = 'red';ball.style.transition = 'left .6s linear, top .6s cubic-bezier(0.5,-0.5,1,1)';document.body.appendChild(ball);// 使用 requestAnimationFrame 替代 setTimeoutrequestAnimationFrame(() => {ball.style.left = box.getBoundingClientRect().left + box.offsetWidth / 2 + 'px';ball.style.top = box.getBoundingClientRect().top + 'px';});ball.ontransitionend = function () {ball.remove();};
}//传入两个参数分别为:当前点击的元素、和小球飞入到盒子的元素
const Qiu = (e, Box) => {const { clientX, clientY } = e;createBall(clientX, clientY, Box)
}export default Qiu; //导出
接下来就是引入js文件,在使用的vue文件中使用
元素部分
<template><div className='xq-all'><!-- //触发小球儿掉落按钮 --><button className='xq-btn' @click="ev=>onchufa(ev)">点击触发</button> <div className='xq-bottom'><!-- //小球掉落的位置 --><p ref="refs">小球儿</p> </div></div>
</template>
逻辑部分
<script setup>
import {ref} from 'vue'
import Qiu from './qiu.js' //引入组件
const refs=ref()const onchufa=(ev)=>{// const { clientX, clientY } = ev;Qiu(ev,refs.value) //在此时用组件中的方法}</script>
样式部分
<style lang="less" scoped>
.xq-all{.xq-btn{float: right;margin: 50px 0;}.xq-bottom{height: 45px;line-height: 45px;width: 100vw;// background-color: bisque;position: fixed;bottom: 200px;left: 200px;p{height: 40px;width: 40px;background-color: aquamarine;margin-left: 30px;font-size: 12px;position: fixed;}}
}
</style>
效果展示:
*************