通过点击按钮 在该位置创建一个小球,然后通过transition和贝塞尔曲线控制小球的抛物线
return (
<div>
<button onClick={(e)=>{handleClick(e)}}
style={{position:'absolute',top:50,left:500,
borderRadius:'50%',border:'none',color:'white',
backgroundColor:'lightblue',
width:25,
height:25,
lineHeight:1,
fontSize:16,
textAlign:'center'}}>+</button>
<button onClick={(e)=>{handleClick(e)}}
style={{
position:'absolute',
top:100,left:500,
borderRadius:'50%',border:'none',color:'white',
backgroundColor:'lightblue',
width:25,
height:25,
lineHeight:1,
fontSize:16,
textAlign:'center'}}>+</button>
<div ref={cart} style={{position:'absolute',left:200,top:500}}>
<img src={Cart} alt="" style={{width:50,height:50}} />
</div>
</div>
)
点击按钮传入事件对象 将clientX、clientY值传给创建小球的函数
const cart=useRef(null)
const handleClick=e=>{
const {clientX,clientY}=e
createBall(clientX,clientY)
}
const createBall=(left,top)=>{
const ball=document.createElement('div')
ball.style.position='absolute'
ball.style.top=top-10+'px'
ball.style.left=left-10+'px'
ball.style.width='10px'
ball.style.height='10px'
ball.style.backgroundColor='red'
ball.style.borderRadius='50%'
ball.style.transition = 'left .6s linear,top .6s cubic-bezier(0.5,-0.5,1,1)';
//x1:在y1为负数情况下,值越大x轴抛出距离越远;取值在0-1之间,否则小球会直接显示在购物车上
//y1:为负值时,值越大,x轴向上抛出距离越远,为正数时,值越大,小球会越紧贴y轴,距离越向下)
//x2:取值在0-1之间,值越大,按钮到购物车之间形成的s形曲线越不明显,取值为1时,形成平滑半U形曲线
//y2:值大于1时:小球会越沿着y轴向下运动再进入购物车
document.body.appendChild(ball)
requestAnimationFrame(()=>{
ball.style.left=cart.current.offsetLeft+cart.current.offsetWidth/2 + 'px'
ball.style.top=cart.current.offsetTop+'px'
})
ball.ontransitionend=function(){
ball.remove()
}
贝塞尔曲线css用法接收四个参数 cubic-bezier(x1,y1,x2,y2) x1 和 x2 必须是 0 到 1 之间的数字。关于cubic-bezier(0.5,-0.5,1,1)参数设置并不是固定的 这样形成的抛物线是比较平滑的 符合应用场景 参数解释只是我的理解 更多信息请参考w3schoolcubic-bezierhttps://www.w3school.com.cn/cssref/func_cubic-bezier.asp以下是 x1=0.5 时的抛物线效果
0.5效果