更生动的排序动画。
通过改变div的高度来实现排序,通过闭包来实现for循环的睡眠时间。
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> button { width:70px; height:30px; background:#005AA8; color:white; font-size:15px; font-family:Microsoft YaHei; border:0; outline:0; border-radius:5px; cursor:pointer; opacity:.8; } button:hover { opacity:1; } #box { width:300px; height:400px; outline:1px solid black; margin-top:10px; } #box div { width:3px; height:200px; margin-left:1px; background:blue; display:inline-block; } #boxboxbox { width:0; height:100%; display:inline-block; margin-left:0px; } </style> </head> <body> <button onclick="fnnn()">排序</button> <div id="box"> <span id="boxboxbox"></span> </div> <script> // div 以及 div 的宽高 var box = document.getElementById("box"); var boxW = box.offsetWidth; var boxH = box.offsetHeight; var len = boxW/4; for(var i = 0;i<len;i++){ var crtDiv = document.createElement("div"); var divH = parseInt(Math.random()*boxH); crtDiv.style.height = divH + "px"; crtDiv.index = i; box.insertBefore(crtDiv,document.getElementById("boxboxbox")); } function fnnn(){ setInterval(fn,300); } function fn(){ var childDiv = box.children; for(var j = 0,leng = childDiv.length-1;j<leng;j++){ for(var n = 0,nleng = childDiv.length-1;n<nleng-j;n++){ (function fun(n){ setTimeout(function(){ if(parseInt(childDiv[n].style.height) > parseInt(childDiv[n+1].style.height)){ var oneH = parseInt(childDiv[n].style.height); childDiv[n].style.height = parseInt(childDiv[n+1].style.height) + "px"; childDiv[n+1].style.height = oneH + "px"; } },n*100); })(n); } } } </script> </body> </html>