Can I use Jquery to automatically find and set the width and height of a variety of images?

筅森魡賤 提交于 2019-12-11 04:08:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!