<style> html, body { margin: 0; padding: 0;} div span { display: inline-block; width: 25px; height: 25px; background: red; } </style>
<div id="wrap"> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div>
<script> function shuffle(aArr) { var iLength = aArr.length , i = iLength , nTemp , iRandom; while ( i-- ) { if (i !== (iRandom = Math.floor(Math.random()*iLength))) { nTemp = aArr[i]; aArr[i] = aArr[iRandom]; aArr[iRandom] = nTemp; }; }; return aArr; }; var oSpans = document.getElementById("wrap").getElementsByTagName("span"); var arr2 = [1, 2, 3, 4, 5, 6]; var flag = true; for (var i = 0, len = oSpans.length; i < len; i++) { oSpans[i].index = i; oSpans[i].onclick = function() { var t = parseInt(Math.random(6)); // 目标坐标 var target = arr2[t]; // 目标值 arr2.splice(t, 1); // 将目标值从数组中删除 shuffle(arr2); // 数组随机排列 var index = this.index; // 获得点击后span的index arr2.splice(index, 0, target); //此时将target插入到arr2中 for (var i = 0, len = oSpans.length; i < len; i++) { oSpans[i].innerHTML = arr2[i]; }; }; }; </script>
时间: 2024-10-10 00:05:55