问题
I am using the Masonry Plugin and for it to work correctly with images, you need to set the width and height within the image tag. All the image's heights will vary, but the width will be set at 200px.
Is there a way for Jquery to detect the height of each image and set it's height? That way I don't have to go set the height of every single image.
Does this make sense?
Hope someone can help! I am new to Jquery.
回答1:
Yes there is, you can use jquery custom selectors like this:
//Add custom selector that returns all objects taller than 200px
//See http://www.bennadel.com/blog/1457-How-To-Build-A-Custom-jQuery-Selector.htm
$.extend($.expr[':'], {
over200pixels: function(a) {
return $(a).height() > 200;
}
});
// Seclect all images taller than 200px
// Set height to 200px using .css() method
// See http://api.jquery.com/css/
$('img:over200pixels').css("height","200px");
Credit where credit is due: jQuery Tips and Tricks
Online demo: http://jsfiddle.net/hvq5m/
来源:https://stackoverflow.com/questions/5239726/can-i-use-jquery-to-automatically-find-and-set-the-width-and-height-of-a-variety