直接上完整代码
import React, { useRef } from 'react';
const ProductLayout = () => {
const box = useRef(null);
const createBall = (left, top) => {
const ball = document.createElement('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)';
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',marginLeft:'200px',marginTop:'300px'}}>
加入购物车
</button>
</div>
<div ref={box} style={{ position: 'fixed', bottom: '50px',left:'550px' }}>
购物车
</div>
</div>
);
};
export default ProductLayout;