console
<!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>
.row span {
padding: 0 5px;
display: inline-block;
}
</style>
</head>
<body>
<div class="row" id="row">
</div>
<button onclick="randomFLIP()">点击打乱</button>
</body>
<script>
const render = (arr) => {
document.getElementById('row').innerHTML = arr.map(v => `<span id="k${v}">${v}</span>`).join('')
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
render(arr)
function shuffle(arr) {
for (var i = arr.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = arr[randomIndex];
arr[randomIndex] = arr[i];
arr[i] = itemAtIndex;
}
return arr;
}
function randomFLIP() {
const randomArr = shuffle(arr)
const firstRect = (() => {
const result = {}
arr.map(v => {
result[`k${v}`] = document.getElementById(`k${v}`).getBoundingClientRect()
})
return result
})()
render(randomArr)
const lastRect = (() => {
const result = {}
randomArr.map(v => {
result[`k${v}`] = document.getElementById(`k${v}`).getBoundingClientRect()
})
return result
})()
arr.forEach(v => {
const first = firstRect[`k${v}`]
const last = lastRect[`k${v}`]
const deltaX = first.left - last.left;
const deltaY = first.top - last.top;
document.getElementById(`k${v}`).style = `transform: translate(${deltaX}px, ${deltaY}px);`
requestAnimationFrame(function () {
document.getElementById(`k${v}`).style = 'transition: all 1s'
document.getElementById(`k${v}`).style.transform = ''
})
})
}
</script>
</html>