代码
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 替代 setTimeoutrequestAnimationFrame(() => {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>);
};export default ProductLayout;
实现效果