react 实现小球加入购物车动画

代码

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 (
        
购物车
); }; export default ProductLayout;

实现效果

react 实现小球加入购物车动画_第1张图片

 

你可能感兴趣的:(javascript,前端,react.js)