import React, { useRef } from 'react'
export default function App() {
const box = useRef(null); // 创建一个引用,用于获取购物车位置的元素
const createBall = (left, top) => { // 创建小球并实现动画效果的函数
const ball = document.createElement('div'); // 创建一个div作为小球元素
// 设置小球的位置
ball.style.position = 'absolute';
ball.style.left = left - 10 + 'px';
ball.style.top = top - 10 + 'px';
// 设置小球的尺寸、形状和颜色等样式
ball.style.width = '20px';
ball.style.height = '20px';
ball.style.borderRadius = '50%';
ball.style.backgroundColor = 'red';
ball.style.transition = 'left .6s linear, top .6s cubic-bezier(0.5,-0.5,1,1)';
// 将小球元素添加到body中
document.body.appendChild(ball);
// 使用 requestAnimationFrame 替代 setTimeout
requestAnimationFrame(() => {
ball.style.left = box.current.offsetLeft + box.current.offsetWidth / 2 + 'px';
ball.style.top = box.current.offsetTop + 'px';
});
// 当小球的过渡动画结束后,移除小球元素
ball.ontransitionend = function () {
ball.remove();
};
};
// 处理'加入购物车'按钮的点击事件
const handleAddToCart = (e) => {
// 获取鼠标点击的坐标信息
const { clientX, clientY } = e;
// 在按钮位置创建小球并实现动画效果
createBall(clientX, clientY);
};
return (
<div>
<div>
<button onClick={(e) => handleAddToCart(e)} style={{ borderRadius: '5px', backgroundColor: '#ff5000', color: 'white' }}>加入购物车</button>
</div>
<div ref={box} style={{ position: 'fixed', bottom: '2px', right: '0' }}>
购物车
</div>
</div>
)
}