使用前确定自己是否已经安装vue3
将下面代码封装到 js文件中:
let createBall = (left, top, box) => {//
const ball = document.createElement('div');
ball.style.position = 'absolute';
ball.style.left = left - 2 + 'px';
ball.style.top = top - 5 + 'px';
ball.style.width = '20px';
ball.style.height = '20px';
ball.style.borderRadius = '20%';
ball.style.backgroundColor = 'green';
ball.style.transition = 'left .6s linear, top .6s cubic-bezier(0.5,-0.5,1,1)';
document.body.appendChild(ball);
//使用 requestAnimationFrame() 方法,这样可以避免一些性能问题
requestAnimationFrame(() => {
获取 box 元素的左边距和顶部距离
ball.style.left = box.getBoundingClientRect().left + box.offsetWidth / 2 + 'px';
ball.style.top = box.getBoundingClientRect().top + 'px';
});
ball.ontransitionend = function () {
ball.remove();
};
}
const Add = (e, Box) => {// e:传递的ev Box:加入的购物车 ref
const { clientX, clientY } = e;
createBall(clientX, clientY, Box)
}
export default Add
前端代码
这是Vue3版本的
<template>
<div>
<div>
<button @click="ev=>mai(ev)">点击</button>
</div>
<div ref="ccc" class="carts">
<h1 >我的车</h1>
</div>
</div>
</template>
<script setup>
import { ref } from "vue"
import Add from "./Vue3封装小球加入购物车动画"
const ccc =ref()
const mai=(ev)=>{
const { clientX, clientY } = ev;
console.log(ccc.value.offsetWidth,"ev",ev.clientX,"x轴",clientX,"y轴",clientY);
console.log(ccc.value.getBoundingClientRect().left + 'px');
Add(ev,ccc.value)
}
</script>
<style scoped>
.carts{
position: relative;
top: 250px;
left: 800px;
width: 100px;
background-color: aqua;
border-radius: 50%;
z-index: 999;
}
</style>