0

Ok so I'm trying to see if an image's width is greater than it's height then apply a class, if not, apply another class.

jQuery('.product_block img').each(function() {
    if(jQuery(this).css('width') > jQuery(this).css('height')) {
        jQuery(this).addClass('product_block_height');
    } else {
        jQuery(this).addClass('product_block_width');
    }
});

Classes:

.product_block_height { height: 100% !important; width: auto !important; }
.product_block_width { width: 100% !important; height: auto !important; }

I'm trying to make it so a div surrounding the image with NO specified height will not squish the image, but the jquery is grabbing the height and width of the image AFTER the surrounding div crops it with the overflow: hidden... I have a responsive grid that has images in a slideshow manner.. and I'm just having trouble saying if the image (ORIGINAL FILE)'s width is greater than the height, then we need the height to expand to the height of the surrounding element and put the width at auto so it doesn't get squished, but keeping in mind that the client can upload ANY image size they want with no restrictions of (MUST BE 350x350).. because the client may not know how to crop images before uploading them.

4

1 回答 1

1

您可以尝试将图像的副本测量到屏幕外元素中。我以前用过这样的东西:

jQuery("<div id='TempImageArea' style='visibility:hidden; position:absolute; z-index:-999; zoom:1; top:-1000px; left:-1000px;'><img id='TempImage' /></div>").appendTo("body");

//Loop through your images
jQuery('.product_block img').each(function() {
    //copy image src to temp image
    var $this = jQuery(this);
    var $tempImage = $("#TempImage");
    var imageSrc = $this.attr("src");
     $tempImage.attr("src", imageSrc);    
    //Test dimensions and add correct class
    if($tempImage.width() > $tempImage.height()) {
        $this.addClass('product_block_height');
    } else {
        $this.addClass('product_block_width');
    }

});

//Remove the off-screen element
jQuery("#TempImageArea").remove();

工作示例:http: //jsfiddle.net/fKxuc/

于 2013-09-10T17:24:26.130 回答