jq实现随机显示部分图片在页面上(兼容IE5)
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> *{ margin:0; padding:0; } ul{ list-style:none; } .outer{ width:196px; margin:20px auto; } .clearfix{ zoom: 1; } .clearfix:after{ content:"."; display:block; width:0; height:0; visibility:hidden; clear: both; } .outer li{ float:left; } </style> </head> <body> <div class="outer"> <ul class="clearfix"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </body> <script src="jquery-1.11.3.min.js"></script> <script> function getAry(ary,num){ var startAry=[],endAry=[]; for(var i=0;i<ary.length;i++){ startAry.push(ary[i]); } for(var j=0;j<num;j++){ if(startAry.length>0){ var arrIndex = Math.floor(Math.random()*startAry.length); /*var arrIndex = Math.round(Math.random()*(startAry.length-1));*/ endAry[j]=startAry[arrIndex]; startAry.splice(arrIndex,1); }else{ break; } } return endAry; } var aryList=[0,1,2,3,4,5,6,7,8,9]; var aryImg=getAry(aryList,6); $("li").each(function(){ var $index=$(this).index(); var oImg="<img src="+'image/0'+aryImg[$index]+'.png'+"/>"; $(this).append(oImg); }) </script> </html>
步骤:
1)首先将所有名片按照相同规则命名(如00.png,01.png,02.png.......)
2)将图片中有规律递增的数字取出来,形成一个数组aryList(如果图片是从00.png到09.png,则建个1-9的数组[0,1,2,3,4,5,6,7,8,9])
3)创建一个方法getAry,将数组aryList和所需显示图片的个数num以形参的形式传入getAry中
4)新建一个数组startAry,并将aryList中的内容克隆到startAry中
5)新建一个数组endAry,随机获取startAry中内容的索引,并将该索引位置处的值放到endAry中(即endAry[j]=startAry[arrIndex])
,然后把startAry中该项值删除,直到放满num个。
6)新建一个数组aryImg,用于存放getAry的执行结果
7)遍历页面中的li,然后新建img标签,赋值后把img标签添加到li中即可
如需添加链接地址,请看下列代码:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> *{ margin:0; padding:0; } ul{ list-style:none; } .outer{ width:196px; margin:20px auto; } .clearfix{ zoom: 1; } .clearfix:after{ content:"."; display:block; width:0; height:0; visibility:hidden; clear: both; } .outer li{ float:left; } </style> </head> <body> <div class="outer"> <ul class="clearfix"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </body> <script src="jquery-1.11.3.min.js"></script> <script> function getAry(ary,url,num){ var startAry=[],startUrl=[],endAry=[],endUrl=[]; for(var i=0;i<ary.length;i++){ startAry.push(ary[i]); startUrl.push(url[i]); } for(var j=0;j<num;j++){ if(startAry.length>0){ var arrIndex = Math.floor(Math.random()*startAry.length); /*var arrIndex = Math.round(Math.random()*(startAry.length-1));*/ endAry[j]=startAry[arrIndex]; endUrl[j]=startUrl[arrIndex]; startAry.splice(arrIndex,1); startUrl.splice(arrIndex,1); }else{ break; } } var aryEnd=[endAry,endUrl]; return aryEnd; } var aryList=[0,1,2,3,4,5,6,7,8,9]; var aryUrl=["0.html","1.html","2.html","3.html","4.html","5.html","6.html","7.html","8.html","9.html"]; var aryImg=getAry(aryList,aryUrl,6); $("li").each(function(){ var $index=$(this).index(); var oImg="<a href="+aryImg[1][$index]+"><img src="+'image/0'+aryImg[0][$index]+'.png'+"/></a>"; $(this).append(oImg); }) </script> </html>