关键技术:animate(keyframes, options)
keyframes 关键帧对象数组,或一个关键帧对象(其属性为可迭代值的数组)
代表动画持续时间的整数(以毫秒为单位),或者一个包含一个或多个时间属性
参考传送门
<!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>
</head>
<style>
* {
padding: 0;
margin: 0;
}
.box {
position: relative;
}
.box div {
position: absolute;
top: 0;
left: 0;
width: 50px;
height: 50px;
border: 10px inset grey;
}
</style>
<body>
<div class="box" onclick="getTag(event)"></div>
</body>
</html>
<script>
// 多少个格子
let btnArr = ["a", "b", "c", "d", "e", "f"];
// 保存点击的两个元素及位置
let saveArr = [];
(function () {
// 获取box
const box = document.querySelectorAll(".box")[0];
// 距离顶部有几个90px
let topNum = 0;
let dom = "";
for (let i = 0; i < btnArr.length; i++) {
if (i % 2 === 0 && i != 0) {
++topNum;
}
dom += `<div class="${btnArr[i]}" style="left:${
i == 0 ? "0px" : i % 2 == 1 ? "90px" : "0px"
};top:${topNum == 0 ? 0 : topNum * 90}px">${btnArr[i]}</div>`;
}
box.innerHTML = dom;
})();
function getTag(e) {
let ele = e.target;
console.dir(ele, "获取到当前点击的元素");
// saveArr <2 添加当前元素
if (saveArr.length < 2) {
let obj = {
ele: ele,
left: ele.offsetLeft,
top: ele.offsetTop,
};
saveArr.push(obj);
}
// saveArr=2 交换两者的位置
if (saveArr.length == 2) {
saveArr[0].ele.animate(
[
{ left: saveArr[0].left + "px", top: saveArr[0].top + "px" },
{ left: saveArr[1].left + "px", top: saveArr[1].top + "px" },
],
{
// 交互时长
duration: 1000,
// 是否停留
fill: "forwards",
// 动画速度
easing: "linear",
}
);
saveArr[1].ele.animate(
[
{ left: saveArr[1].left + "px", top: saveArr[1].top + "px" },
{ left: saveArr[0].left + "px", top: saveArr[0].top + "px" },
],
{
duration: 1000,
easing: "linear",
fill: "forwards",
}
);
// 清空saveArr
saveArr = [];
}
}
</script>