<!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>
<link
rel="stylesheet"
href="https://at.alicdn.com/t/c/font_3962024_7b50c2a5js9.css"
/>
<style>
html,
body {
padding: 0;
margin: 0;
overflow: hidden;
}
.biu {
position: fixed;
}
.bar {
position: fixed;
bottom: 0;
width: 100%;
border-top: #eeeeee solid 1px;
display: flex;
align-self: center;
padding: 10px;
z-index: 2;
}
.icon-gouwuchekong {
font-size: 20px;
position: relative;
left: 100px;
}
</style>
</head>
<body>
<ul>
<li>商品1 <button>加入购物车</button></li>
<li>商品2 <button>加入购物车</button></li>
</ul>
<div class="bar">
<i class="iconfont icon-gouwuchekong"></i>
</div>
<script>
// 获取元素的绝对位置坐标(像对于页面左上角)
function getElementPagePosition(element) {
//计算x坐标
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null) {
actualLeft += current.offsetLeft;
current = current.offsetParent;
}
//计算y坐标
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null) {
actualTop += current.offsetTop + current.clientTop;
current = current.offsetParent;
}
//返回结果
return { x: actualLeft, y: actualTop };
}
document.body.addEventListener("click", (e) => {
if (e.target.nodeName === "BUTTON") {
// 创建biu元素
const biu = document.createElement("div");
biu.className = "biu";
biu.style.left = e.pageX + "px";
biu.style.top = e.pageY + "px";
biu.style.transform = "scale(1)";
biu.appendChild(e.target.parentNode.cloneNode(true));
document.body.appendChild(biu);
// 计算购物车的位置
const carEl = document.querySelector(".icon-gouwuchekong");
const carElPostion = getElementPagePosition(carEl);
const needLeft = (carElPostion.x - parseInt(window.getComputedStyle(biu).width)/2)
// 将biu元素抛到购物车里
biu.style.transition = "left 0s, top 0s, transform 0s";
setTimeout(() => {
biu.style.top = carElPostion.y + "px";
biu.style.left = Number(needLeft) + "px";
biu.style.transform = "scale(0)";
biu.style.transition =
"left 1s linear, top 1s ease-in, transform 1.2s linear";
setTimeout(() => {
biu.remove();
}, 1000);
}, 20);
}
});
</script>
</body>
</html>
标签:动画,style,top,购物车,current,添加,element,biu
From: https://www.cnblogs.com/dingshaohua/p/17233017.html