JS冒泡排序(div)

更生动的排序动画。

通过改变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>

 

转载于:https://www.cnblogs.com/chefweb/p/6219539.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值