<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #wrap{ position: relative; list-style: none; margin: 0 auto; } #wrap li{ width: 200px; font-size: 1.5rem; position: absolute; background-color: #CCCCCC; -webkit-transition: all 2s; } #wrap li div{ width: 100%; height: 100%; overflow: hidden; } </style> </head> <body> <ul id="wrap"></ul> </body> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript"> $(function(){ function randomFunction(max , min){ return parseInt(Math.random() * (max - min)) + min; } var wrapUL = document.getElementById("wrap"); var width = 200; var rightPadding = 10; var hs = []; var num = 0; function setLiPos(bol){ var lis = wrapUL.getElementsByTagName("li"); var windowBody = document.documentElement.clientWidth; var cols = parseInt(windowBody / width); wrapUL.style.width = cols * (width + rightPadding) + "px"; var arrT = []; for (var i = 0; i < cols; i++) { arrT[i] = 0; } function createLi(index){ var li = lis[index]||document.createElement("li"); var h = hs[index] || randomFunction(100, 300); li.style.height = h + "px"; if(bol){ hs.push(h); } var min = arrT[0]; var minIndex = 0; for (var i = 0; i < arrT.length; i++) { if(min > arrT[i]){ min = arrT[i]; minIndex = i; } } li.style.top = arrT[minIndex] + "px"; li.style.left = minIndex * (width + rightPadding) + "px"; arrT[minIndex] += (h + rightPadding); bol&&wrapUL.appendChild(li); } for(var i = 0; i < 20; i++){ if(bol){ num++; } createLi(i); } } setLiPos(true); window.onresize = function(){ setLiPos(false); } }); </script> <script type="text/javascript"> $(function(){ var imgArr = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg"]; $("li").each(function(index, el) { var n = RandomNumBoth(0,imgArr.length-1); var imgsrc = imgArr[n]; $(this).html("<div><img onload=‘loadImage()‘ src=‘"+imgsrc+"‘></div>"); }); }); function loadImage(){ $("img").each(function(index, el) { var a=$(this).width(), b=$(this).height(), pa = $(this).parent().width(), pb = $(this).parent().height(), e=a/b, //图片宽高比 3 pe=pa/pb; //承载图片容器宽高比 if(e>=pe){ $(this).css({height:"100%",width:"auto"}); var imgW = $(this).width(), iW = $(this).parent().width(), w = -(imgW - iW)/2; $(this).css(‘marginLeft‘,w); }else{ $(this).css({width:"100%",height:"auto"}); var imgH = $(this).height(), iH = $(this).parent().height(), h = -(imgH - iH)/2; $(this).css(‘marginTop‘,h); } }); } function RandomNumBoth(Min,Max){ var Range = Max - Min; var Rand = Math.random(); var num = Min + Math.round(Rand * Range); return num; } </script> </html>
时间: 2024-11-05 18:59:34