<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
@keyframes moveX {
to {
transform: translateX(var(--x));
}
}
@keyframes moveY {
to {
transform: translateY(var(--y));
}
}
.plus {
position: fixed;
top: var(--top);
left: var(--left);
width: 30px;
height: 30px;
border-radius: 50%;
cursor: pointer;
animation: moveY 0.75s cubic-bezier(0.5, -0.5, 1, 1);
}
.plus-icon {
width: 100%;
height: 100%;
background-color: red;
border-radius: 50%;
animation: moveX 0.75s linear;
}
.car {
width: 60px;
height: 60px;
display: flex;
justify-content: center;
align-items: center;
position: fixed;
left: 240px;
bottom: 100px;
color: white;
border-radius: 50%;
background-color: #5151e7;
}
button {
border: 0;
background-color: #5151e7;
border-radius: 10px;
position: fixed;
top: 100px;
right: 20px;
color: white;
padding: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<button>加入购物车</button>
<div class="car">购</div>
</body>
<script>
let btn = document.querySelector("button");
let car = document.querySelector(".car");
let PLUS_SIZE = 30;
btn.onclick = () => {
let box = document.createElement("div");
box.className = "plus";
box.innerHTML = "<div class='plus-icon'></div>";
let btnRect = btn.getBoundingClientRect();
let left = btnRect.left + btnRect.width / 2 - PLUS_SIZE / 2;
let top = btnRect.top - PLUS_SIZE;
let carRect = car.getBoundingClientRect(); //返回的是矩形的集合
//表示了当前盒子在浏览器中的位置以及自身占据的空间的大小,除了 width 和 height 之外
//其他的属性是相对于视图窗口的左上角 来计算的
//该函数返回一个Object对象,该对象有6个属性:top,lef,right,bottom,width,height;
let x = carRect.left + carRect.width / 2 - PLUS_SIZE / 2 - left;
let y = carRect.top - PLUS_SIZE - top;
box.style.setProperty("--left", `${left}px`);
box.style.setProperty("--top", `${top}px`);
box.style.setProperty("--x", `${x}px`);
box.style.setProperty("--y", `${y}px`);
box.addEventListener("animationend", () => {
//当 CSS 动画完成时删除小球
box.remove();
});
document.body.appendChild(box);
};
</script>
</html>
也可以将小球设置为商品的缩略图 增加用户体验