问题描述:

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
        }
    });
})
网友答案:

You can also check out 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.

相关阅读:
Top