目的呢是做一个类似如图的样子 有意思就记录一下
![]()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| const testArr = Array.from({length: 10}).map(()=> Math.round(Math.random() * 10));
function bubble(testArr) { const arr = testArr.slice(); const operationList = []; for(let i = 0; i < testArr.length; i++) { for(let j = i + 1; j < testArr.length; j++) { if(arr[i] > arr[j]){ [arr[i], arr[j]] = [arr[j], arr[i]] operationList.push({ from: i, to: j, array: arr.slice(), }) } } } return operationList; }
var container = document.getElementById('container');
var collect = document.createDocumentFragment('div'); var spanList = []; for(let i = 0; i < testArr.length; i++) { var span = document.createElement('span'); span.className = 'square'; span.innerText = testArr[i]; span.style.left = i * 40 + 'px'; spanList[i] = span; collect.appendChild(span); }
container.appendChild(collect);
for(let j = 0; j < result.length; j++) { setTimeout(function() { const fromIndex = result[j].from; const toIndex = result[j].to; const tmp = spanList[toIndex].style.left;
spanList[toIndex].style.left = spanList[fromIndex].style.left; spanList[fromIndex].style.left = tmp; [spanList[toIndex], spanList[fromIndex]] = [spanList[fromIndex], spanList[toIndex]] }, 1000 * j) }
|
配合上css的transition属性,就可以做到简单的动画效果啦
演示地址:点击查看
// 打开控制台 数据显示更清晰