创建JS文件
let createBall = (left, top, box) => {
//获取的是div外层需要div包裹
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 = "red";
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代码
<script setup>
import { ref } from "vue";
//引入JS文件
import Add from "./Add";
const car = ref();
//点击按钮事件
const onClick = (ev) => {
mai(ev);
};
const mai = (ev) => {
const { clientX, clientY } = ev;
console.log(
car.value.offsetWidth,
"ev",
ev.clientX,
"x轴",
clientX,
"y轴",
clientY
);
console.log(car.value.getBoundingClientRect().left + "px");
Add(ev, car.value);
};
</script>
<template>
<div>
<div class="balls">
<!-- 点击事件发送小球 -->
<button @click="onClick($event)">点击</button>
</div>
<div ref="car" class="carts">
<h1>我的车</h1>
</div>
</div>
</template>
CSS代码:
.balls {
position: relative;
top: 70px;
}
.carts {
position: relative;
top: 550px;
left: 250px;
width: 100px;
background-color: green;
border-radius: 50%;
z-index: 999;
}