今天和大家分享一个购物车动效的实现方案,简单有效(づ ̄3 ̄)づ╭❤~
// 动态创建加入购物车的元素和动画
const createBall = (left, top) => {
return new Promise((reslove) => {
const bar = document.createElement('bar')
const lableBtn = document.querySelector('#my-shopping-cart-box')
let rect = lableBtn.getBoundingClientRect() // 获取统计按钮位置
let size = [lableBtn.clientWidth, lableBtn.clientHeight] // 统计按钮本身高、宽
const afterX = rect.x + size[0] / 2 // 计算小球最后的位置x
const afterY = rect.y - size[1] / 2 // 计算小球最后的位置Y
bar.classList = ['add-shoppiing-cart-bar']
bar.style.position = 'fixed'
bar.style.left = left + 'px'
bar.style.top = top + 'px'
bar.style.zIndex = '9999'
// 实现效果的核心代码
bar.style.transition = 'left 2s cubic-bezier(0.5, -0.5, 1, 1), top 1.3s linear'
bar.innerHTML = '+999'
document.body.appendChild(bar)
setTimeout(() => {
const x = afterX
const y = afterY
bar.style.top = y + 'px'
bar.style.left = x + 'px'
}, 100) /* 经实践,定时器时间间隔需要设置一定的时间间隔才有效果,设置为0无效果 */
bar.ontransitionend = function () {
const targetEle = document.querySelector('.add-shoppiing-cart-bar')
document.body.removeChild(targetEle)
reslove()
}
})
}
// 点击加入购物车事件
const handleAddCart = useDebounceFn(async (event) => {
const x = event.clientX - 20
const y = event.clientY - 20
await createBall(x, y)
// 调用新增购物车的商品的接口
await addCart()
}, 500)
.add-shoppiing-cart-bar {
width: 20px;
height: 20px;
border-radius: 50%;
z-index: 99;
color: red;
}
tips
:在实现的过程中的踩了个坑,本来改位置的setTimeout
定时器的延时设置为0
的,试了半天没效果,还以为这个实现思路不行,后面将定时器设为一个大一点的数字才有了效果。