图片排序

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script type="text/javascript">
window.onload = function ()
{
    var oli = document.getElementById('btn').getElementsByTagName('li');
    var obox = document.getElementById('box');
    var ali = obox.getElementsByTagName('li');
    var arr = [];
    var onff = 1;
    
    for (var i = 0; i < ali.length; i++ )
    {
        arr.push(ali[i]);
    }
    
    oli[0].onclick = function ()
    {
        arr.reverse();
        var str = '';
        for( var i = 0; i < arr.length; i++)
        {
            str += '<li>' +arr[i].innerHTML + '</li>';
        }
        obox.innerHTML = str;
        
        this.innerHTML = onff?'从小到大':'从大到小';
        onff = !onff;
    }
    
    oli[1].onclick = function ()
    {
        var arr2 = [];
        for (var i = 0; i < ali.length; i++)
        {
            arr2.push(ali[i]);
        }
        arr2.sort(function (a,b)
        {
            return Math.random()-0.5;
        });
        var str = '';
        for( var i = 0; i < ali.length; i++ )
        {
            str += '<li>' + arr2[i].innerHTML +'</li>';
        }
        obox.innerHTML = str;
    };
    
    
}
</script>
<style>
*{
    margin:0px;
    padding:0px;
    list-style-type:none;
    }
#btn{
    width:1000px;
    height:60px;
    background:#F1F1F1;
    margin:0 auto;
    text-align:center;
    }
#btn li{
    display:inline-block;
    background:#009999;
    color:#fff;
    padding:8px 20px;
    font-size:14px;
    font-weight:bold;
    font-family:"微软雅黑";
    margin-top:12px;
    cursor:pointer;
    }
#box{
    width:988px;
    margin:0px auto;
    background:#F1F1F1;
    overflow:hidden;
    padding:10px;
    }
#box li{
    float:left;
    padding:10px;
    background:#fff;
    border:1px solid #f1f1f1;
    }
h2{
    font-family:"微软雅黑";
    font-size:16px;
    font-weight:bold;
    color:#00518D;
    text-align:center;
    background:#f1f1f1;
    padding-top:5px;
    padding-bottom:5px;
    }    
img{
    width:225px;
    height:145px;
    }                
</style>
</head>

<body>
<ul id="btn">
    <li>从大到小</li>
    <li>打乱顺序</li>
</ul>
<ul id="box">
    <li>
        <img src="img/5-1.jpg">
        <h2>图片1</h2>
    </li>
    <li>
        <img src="img/5-2.jpg">
        <h2>图片2</h2>
    </li>
    <li>
        <img src="img/5-3.jpg">
        <h2>图片3</h2>
    </li>
    <li>
        <img src="img/5-4.jpg">
        <h2>图片4</h2>
    </li>
    <li>
        <img src="img/5-5.jpg">
        <h2>图片5</h2>
    </li>
    <li>
        <img src="img/5-6.jpg">
        <h2>图片6</h2>
    </li>
    <li>
        <img src="img/5-7.jpg">
        <h2>图片7</h2>
    </li>
    <li>
        <img src="img/5-8.jpg">
        <h2>图片8</h2>
    </li>
</ul>
</body>
</html>

学习了sort 和 reverse

return a-b  从小到大

return b-a 从大到小

return Math.random()-0.5 随机数

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

以上

posted @ 2014-12-29 23:21  mayufo  阅读(271)  评论(0编辑  收藏  举报