Gallery images visible based on screen size
I need a photography gallery to display in 3 rows, each row showing different number of images. Not all images have the same width. When the screen resizes I want more images to show, but in the same ratio (grow to 3/5/4, 4/6/5, etc...). The ratio should be like this (brackets represent an image):
[][]
[][][][]
[][][]
Visual example here.
It was partly working except for the offset. I tried 开发者_运维问答to write an offset loop, and now it's not working at all. Here is the code:
<script>
jQuery(document).ready(function() {
jQuery('.gallery').wrap('<div class="gal-wrapper" />');
resizeGallery("#gallery-1",2);
resizeGallery("#gallery-2",4);
resizeGallery("#gallery-3",3);
});
jQuery(window).resize(function() {
resizeGallery("#gallery-1",2);
resizeGallery("#gallery-2",4);
resizeGallery("#gallery-3",3);
});
function resizeGallery(gall, initpos){
var x = 0;
var y = 0;
var accum_width = 0;
var final_width = accum_width;
var offset = initpos;
var wW = jQuery(window).width()-jQuery("#nav").width();
while(accum_width < wW){
var new_width = jQuery(gall).find("img.attachment-medium:eq("+x+")").width();
if((accum_width + new_width) > wW){
break;
}else{
accum_width += new_width+4;
}
x++;
}
/* worked partly to this point... onto the offset! */
while(y < offset){
var subtract_width = jQuery(gall).find("img.attachment-medium:eq("+x+")").width();
final_width -= subtract_width+4;
y++;
x--;
}
jQuery(gall).parent().width(final_width);
}
</script>
Here is a jsfiddle example.
Your working JS fiddle
In case That fiddle link doesn't work...
jQuery(document).ready(function() {
jQuery('.gallery').wrap('<div class="gal-wrapper" />');
var picCount = resizeGallery("#gallery-2", Number.POSITIVE_INFINITY);
resizeGallery("#gallery-3", picCount-1);
resizeGallery("#gallery-1", picCount-2);
});
jQuery(window).resize(function() {
var picCount = resizeGallery("#gallery-2", Number.POSITIVE_INFINITY);
resizeGallery("#gallery-3", picCount-1);
resizeGallery("#gallery-1", picCount-2);
});
function resizeGallery(gall, picCount) {
var x = 0;
var y = 0;
var accum_width = 0;
var wW = jQuery(window).width() - jQuery("#nav").width();
while (accum_width < wW && x < picCount) {
var new_width = jQuery(gall).find("img.attachment-medium:eq(" + x + ")").width();
if ((accum_width + new_width) > wW) {
break;
} else {
accum_width += new_width + 4;
}
x++;
}
jQuery(gall).parent().width(accum_width);
return x;
}
精彩评论