简体   繁体   中英

jQuery resize all images on document ready by class

I have a page with images which I want them all to be resized (by acquiring certain CSS classes) on document ready using jQuery. The images have an initial ".test" which has no attributes in the CSS file. I know how to give them the new classes so they can be resized. But, I want to resize depending on width or height so they can all look the same.

My problem is that I cannot get their width/height to proceed. My code is this:

$(document).ready(function(){

    $('.test').each(function(){
        var img_width = $(this).width();
        var img_height = $(this).height();
        alert("My width:" + img_width + "px, My Height: " + img_height + "px");

        if (img_width > img_height)
        {
            //resize to height
        }else{
            //resize to width
        }
    });
})

The alert I have before the if statement always returns 0 - although it does appear the correct number of times.

I also tried getting the width (and also the height) with $(this).width; and $(this).offsetHeight; and $(this).attr('width'); but when the result is not 0, it's undefined .

What am I doing wrong?

Use

$(window).load(function() {

instead of

$(document).ready(function(){

The load event is triggered a bit later when all the images have actually loaded.

use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.

Source: http://api.jquery.com/ready/

$(document).ready(function(){

    $('.test').load(function(){
        var img_width = $(this).width();
        var img_height = $(this).height();
        alert("My width:" + img_width + "px, My Height: " + img_height + "px");

        if (img_width > img_height)
        {
            //resize to height
        }else{
            //resize to width
        }
    });
})

您还可以签出SLIR: https : //github.com/lencioni/SLIR

I ran across this problem a while ago too. The problem is that the images are not fully loaded yet.

However, I would suggest NOT to do it this way. Loading a big picture, then resize it clientside is not a good method. You should consider resizing it serverside so users don't have to download large images for no use.

You should take a look at phpThumb, which is a great PHP-class that resizes and caches the images for you. It's a great tool and a much better way to achieve this.

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