<div class="cart">
购
</div>
<button>加入购物车</button>
html {
--color: #02B6FD;
--time: 0.5s;
}
.cart {
position: absolute;
width: 60px;
height: 60px;
border-radius: 50%;
color: white;
background-color: var(--color);
display: flex;
align-items: center;
justify-content: center;
bottom: 30px;
left: 30px;
transition: transform 0.1s;
}
.active {
transform: scale(1.2);
}
button {
position: absolute;
right: 30px;
top: 100px;
padding: 0 10px;
line-height: 30px;
border-radius: 4px;
border: none;
background-color: var(--color);
color: white;
}
.plus {
position: absolute;
left: var(--left);
top: var(--top);
animation: moveY var(--time) cubic-bezier(0.5, -0.5, 1, 1);
}
.plus>span {
display: inline-block;
width: 20px;
height: 20px;
background-color: var(--color);
border-radius: 50%;
color: white;
line-height: 20px;
text-align: center;
animation: moveX var(--time) linear;
}
@keyframes moveY {
to {
transform: translateY(var(--y));
}
}
@keyframes moveX {
to {
transform: translateX(var(--x));
}
}
const cart = document.querySelector('.cart')
const btn = document.querySelector('button')
const WIDTH = 20
btn.onclick = () => {
const div = document.createElement('div')
div.className = 'plus'
div.innerHTML = '<span>+</span>'
const btnRect = btn.getBoundingClientRect()
const left = btnRect.left + btnRect.width / 2 - WIDTH / 2
const top = btnRect.top - WIDTH
const cartRect = cart.getBoundingClientRect()
const x = cartRect.left + cartRect.width / 2 - WIDTH / 2 - left
const y = cartRect.top + WIDTH - top
div.style.setProperty('--left', `${left}px`)
div.style.setProperty('--top', `${top}px`)
div.style.setProperty('--x', `${x}px`)
div.style.setProperty('--y', `${y}px`)
div.addEventListener('animationend', () => {
div.remove()
cart.className = 'cart active'
setTimeout(() => {
cart.className = 'cart'
}, 100)
})
document.body.appendChild(div)
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.