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;
react.js代码
import React, { useRef } from "react";
//引入我们的js文件
import Add from "./Add";
//引入style样式
import "./style.css";
export default function Ball() {
const carRef = useRef(null);
const mai = (ev) => {
const { clientX, clientY } = ev;
console.log(
carRef.current.offsetWidth,
"ev",
ev.clientX,
"x轴",
clientX,
"y轴",
clientY
);
console.log(carRef.current.getBoundingClientRect().left + "px");
Add(ev, carRef.current);
};
return (
<div>
<div className="balls">
<button
onClick={($event) => {
mai($event);
}}
>
按钮
</button>
<div ref={carRef} className="carts">
<h1>我的车</h1>
</div>
</div>
</div>
);
}
style样式
*{
padding: 0;
margin: 0;
}
.balls {
position: relative;
top: 70px
}
.carts {
position: relative;
top: 550px;
left: 250px;
width: 100px;
background-color: green;
border-radius: 50%;
z-index: 999;
}