以下是 jQuery响应浏览器窗口大小图片排列代码 的示例演示效果:
部分效果截图:
HTML代码(index.html):
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery响应浏览器窗口大小图片排列代码</title>
<link rel="stylesheet" type="text/css" href="css/normalize.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.mosaic.css">
</head>
<body>
<div id="mosaic" class="mosaic">
<img src="images/1.jpg" data-high-res-image-src="images/1.jpg" width="640" height="480" />
<img src="images/2.jpg" data-high-res-image-src="images/2.jpg" width="640" height="480" />
<img src="images/3.jpg" data-high-res-image-src="images/3.jpg" width="640" height="426" />
<img src="images/4.jpg" data-high-res-image-src="images/4.jpg" width="640" height="410" />
<img src="images/5.jpg" data-high-res-image-src="images/5.jpg" width="640" height="426" />
<img src="images/6.jpg" data-high-res-image-src="images/6.jpg" width="640" height="359" />
</div>
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.mosaic.js"></script>
<script type="text/javascript">
$('#mosaic').Mosaic({
maxRowHeight: 600,
highResImagesWidthThreshold: 640
});
</script>
</body>
</html>
JS代码(jquery.mosaic.js):
/* jQuery Mosaic v0.12 https://github.com/tin-cat/jquery-mosaic A jquery plugin by Tin.cat to build beautifully arranged and responsive mosaics of html elements maintaining their original aspect ratio. Works wonderfully with images by creating a visually ordered and pleasant mosaic (much like mosaics on Flickr,500px and Google+) without gaps between elements,but at the same time respecting aspect ratios. Reacts to window resizes and adapts responsively to any screen size. See it working on https://skinography.net */
(function($){
$.Mosaic = function(el,options){
var base = this,o;
base.el = el;
base.$el = $(el);
base.$el.data('Mosaic',base);
var baseWidth;
var refitTimeout = false;
base.init = function(){
base.options = o = $.extend({
}
,$.Mosaic.defaults,options);
$(base.el).addClass("mosaic");
if (o.outerMargin) $(base.el).css('padding',o.outerMargin);
if (o.innerGap) $(base.el).css('margin-bottom',o.innerGap * -1);
base.fit();
if (o.refitOnResize) $(window).on('resize',null,null,function(){
if (o.refitOnResizeDelay){
if (refitTimeout) clearTimeout(refitTimeout);
refitTimeout = setTimeout(function(){
base.fit()}
,o.refitOnResizeDelay);
}
else base.fit()}
);
}
base.getItems = function(){
return $('> div:not([data-no-mosaic=true]),> a:not([data-no-mosaic=true]),> img:not([data-no-mosaic=true])',base.el);
}
base.getItemAtIndex = function(index){
if (!base.getItems()[index]) return false;
return $(base.getItems()[index]);
}
base.getItemsSubset = function(start,numberOf){
var items = base.getItems();
if (start > items.length) return false;
if (start + numberOf > items.length) numberOf = items.length - start;
return items.slice(start,start + numberOf);
}
base.isLastItemsSubset = function(start,numberOf){
var items = base.getItems();
if (start > items.length) return true;
if (start + numberOf > items.length) return true;
return false;
}
base.getItemWidth = function(item){
return $(item).attr('width');
}
base.getItemHeight = function(item){
return $(item).attr('height');
}
base.getItemAspectRatio = function(item){
if ($(item).data('aspect-ratio')) return $(item).data('aspect-ratio');
if (base.getItemWidth(item) && base.getItemHeight(item)) return base.getItemWidth(item) / base.getItemHeight(item);
return o.defaultAspectRatio;
}
base.getItemWidthForGivenHeight = function(item,height){
return height * base.getItemAspectRatio(item);
}
base.getItemHeightForGivenWidth = function(item,width){
return width / base.getItemAspectRatio(item);
}
base.setItemSizeByGivenHeight = function(item,height){
var width = Math.floor(base.getItemWidthForGivenHeight(item,height));
$(item) .css('height',Math.floor(height)) .css('width',width);
if (o.highResImagesWidthThreshold){
if (width > o.highResImagesWidthThreshold){
var highResBackgroundImage = $(item).data('high-res-background-image-url');
if ( highResBackgroundImage && !$(item).data('low-res-background-image-url') ){
$(item).data('low-res-background-image-url',$(item).css('background-image'));
$(item).css('background-image','url("' + highResBackgroundImage + '")');
$(item).addClass('highRes');
}
var highResImage = $(item).data('high-res-image-src');
if ( highResImage && !$(item).data('low-res-image-src') ){
$(item).data('low-res-image-src',$(item).attr('src'));
$(item).attr('src',highResImage);
$(item).addClass('highRes');
}
}
else{
var lowResBackgroundImage = $(item).data('low-res-background-image-url');
if (lowResBackgroundImage){
$(item).css('background-image',lowResBackgroundImage);
$(item).data('low-res-background-image-url',false);
$(item).removeClass('highRes');
}
var lowResImage = $(item).data('low-res-image-src');
if (lowResImage){
$(item).attr('src',lowResImage);
$(item).data('low-res-image-src',false);
$(item).removeClass('highRes');
}
}
}
return width;
}
base.calculateHeightToFit = function(items){
var sumAspectRatios = 0;
items.each(function(){
sumAspectRatios += parseFloat(base.getItemAspectRatio(this));
}
);
return (baseWidth - (o.innerGap * (items.length - 1))) / sumAspectRatios;
}
base.retrieveBaseWidth = function(){
baseWidth = $(base.el).width();
}
base.fit = function(){
base.retrieveBaseWidth();
var items,height;
var itemsToUse = 1;
var startIndex = 0;
var isAnyFitted = false;
while (true){
items = base.getItemsSubset(startIndex,itemsToUse);
if (base.isLastItemsSubset(startIndex,itemsToUse)){
if (items.length){
base.fitItems(items);
}
break;
}
height = base.calculateHeightToFit(items);
if (height > o.maxRowHeight){
itemsToUse ++;
continue;
}
base.fitItems(items);
startIndex += itemsToUse;
itemsToUse = 1;
isAnyFitted = true;
}
// If maxRowHeight has not been met at any point (might happen when specifying short maxRowHeights) if (!isAnyFitted) base.fitItems(base.getItems());
}
base.fitItems = function(items){
var height = base.calculateHeightToFit(items);
if (height > o.maxRowHeight){
switch (o.maxRowHeightPolicy){
case 'skip':items.each(function(){
$(this).hide();
}
);
return;
break;
case 'crop':height = o.maxRowHeight;
break;
case 'oversize':// Do nothing break;
}
}
items.each(function(){
$(this).show();
}
);
var accumulatedWidth = 0;
items.each(function(idx){
accumulatedWidth += base.setItemSizeByGivenHeight(this,height);
if (o.innerGap){
$(this).css('margin-right',idx < items.length - 1 ? o.innerGap:0);
$(this).css('margin-bottom',o.innerGap);
}
}
);
// Enlarge a bit the last element to compensate for accumulated floored decimal widths leaving a gap at the end if (accumulatedWidth < baseWidth) items.last().css('width',items.last().width() + ((baseWidth - ((items.width - 1) * o.innerGap) ) - accumulatedWidth) );
}
base.init();
}
$.Mosaic.defaults ={
maxRowHeight:400,// The maximum desired height of rows refitOnResize:true,// Whether to rebuild the mosaic when the window is resized or not refitOnResizeDelay:false,// Milliseconds to wait after a resize event to refit the mosaic. Useful when creating huge mosaics that can take some CPU time on the user's browser. Leave it to false to refit the mosaic in realtime. defaultAspectRatio:1,// The aspect ratio to use when none has been specified,or can't be calculated maxRowHeightPolicy:'skip',// Sometimes some of the remaining items cannot be fitted on a row without surpassing the maxRowHeight. For those cases,choose one of the available settings for maxRowHeightPolicy:"skip":Does not renders the unfitting items. "crop":caps the desired height to the specified maxRowHeight,resulting in those items not keeping their aspect ratios. "oversize":Renders the items respecting their aspect ratio but surpassing the specified maxRowHeight highResImagesWidthThreshold:350,// The item width on which to start using the the provided high resolution image instead of the normal one. High resolution images are specified via the "data-high-res-image-src" or "data-high-res-background-image-url" html element properties of each item. outerMargin:0,// A margin size in pixels for the outher edge of the whole mosaic innerGap:0 // A gap size in pixels to leave a space between elements}
;
$.fn.Mosaic = function(options,params){
return this.each(function(){
var me = $(this).data('Mosaic');
if ((typeof(options)).match('object|undefined')) new $.Mosaic(this,options);
elseeval('me.'+options)(params);
}
);
}
}
)(jQuery);
CSS代码(jquery.mosaic.css):
/* jQuery Mosaic v0.12 https://github.com/tin-cat/jquery-mosaic */
.mosaic{width:100%;float:left;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;overflow:hidden;}
.mosaic > div,.mosaic > a,.mosaic > img{float:left;}
.mosaic > .item{position:relative;}
.mosaic > .item.withImage{background-size:cover;}
.mosaic > .item > .overlay{opacity:0;position:absolute;left:0px;right:0px;top:0px;bottom:0px;transition:opacity .2s ease-in-out;-moz-transition:opacity .2s ease-in-out;-webkit-transition:opacity .2s ease-in-out;}
.mosaic > .item:hover > .overlay{opacity:1;}
.mosaic > .item > .overlay > .texts{position:absolute;left:0px;right:0px;bottom:0px;padding:15pt;background:rgba(0,0,0,0.2);color:#fff;}
.mosaic > .item > .overlay > .texts h1,.mosaic > .item > .overlay > .texts h2{margin:0;line-height:1.3em;}
.mosaic > .item > .overlay > .texts h1{font-size:17pt;}
.mosaic > .item > .overlay > .texts h2{font-size:13pt;}
CSS代码(normalize.css):
article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block;}
audio,canvas,video{display:inline-block;}
audio:not([controls]){display:none;height:0;}
[hidden]{display:none;}
html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;}
body{margin:0;}
a:focus{outline:thin dotted;}
a:active,a:hover{outline:0;}
h1{font-size:2em;margin:0.67em 0;}
abbr[title]{border-bottom:1px dotted;}
b,strong{font-weight:bold;}
dfn{font-style:italic;}
hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0;}
mark{background:#ff0;color:#000;}
code,kbd,pre,samp{font-family:monospace,serif;font-size:1em;}
pre{white-space:pre-wrap;}
q{quotes:"\201C" "\201D" "\2018" "\2019";}
small{font-size:80%;}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline;}
sup{top:-0.5em;}
sub{bottom:-0.25em;}
img{border:0;}
svg:not(:root){overflow:hidden;}
figure{margin:0;}
fieldset{border:1px solid #c0c0c0;margin:0 2px;padding:0.35em 0.625em 0.75em;}
legend{border:0;padding:0;}
button,input,select,textarea{font-family:inherit;font-size:100%;margin:0;}
button,input{line-height:normal;}
button,select{text-transform:none;}
button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer;}
button[disabled],html input[disabled]{cursor:default;}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0;}
input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box;}
input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none;}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0;}
textarea{overflow:auto;vertical-align:top;}
table{border-collapse:collapse;border-spacing:0;}