简体   繁体   中英

Check the width of all images and set new width if over a certain size

I have a page with several images that have the same class ".bestsell-thumb" . How can I make all these images into an array, then get each ones width and if it's greater than 80px change it to 80px?

I tried this

var  bsThumb = $(".bestsell-thumb").each(function(){
             $(this).height();
});

just to get the heights, but I'm pretty sure I'm way off.

Thanks for any help.

$(".bestsell-thumb").width(function(i, w) {
    return w > 80 ? 80 : w;
});

They do of course have to be loaded before you can get anything!

Try

$(".bestsell-thumb").each(function(){
    if ($(this).width() > 80) {
        $(this).css("width", "80px");
    }
});

You can try:

$(".bestsell-thumb").each(function(){
    if($(this).width() > 80){
        $(this).width("80px");
    }
});

Use CSS instead of JavaScript:

.bestsell-thumb {
  max-width: 80px;
  height: auto; /* maintains proportions */
}

You can set max-height in the same style block, too -- just set width: auto as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM