I'm trying to get the width/height of an image in order to set the width/height of the parent container. This is my code to do so:
var current_img = temp.find(".test-img").attr('src', c['img']).addClass("active-image");
Then I get the image width/height via
current_img.css('width');
The issue I'm running into is chrome loads the jscript before the images, so the function is returning null. So I put together this code:
$(".test-img").each(function (index) {
$(this).load(function() {
imgwidth = $(this).css('width');
imgheight = $(this).css('height');
if (imgwidth != "0px" && imgheight != "0px")
$(this).parent().addClass('center').css({'width' : imgwidth, 'height' : imgheight});
});
});
This seems to work fine the first time you load the page, but whe开发者_StackOverflow中文版n the function is called it returns null. Also when I open the page locally it seems to work fine but when hosted on my webserver I get this problem.
Here is the page in question: http://swolepersonaltraining.com/testing/sorter/
Ok so after a lot of research I was able to find a solution. This isn't perfect but the best I've come up with so far.
var img = new Image(); //create new image
$(img).append("div").fadeIn('fast', function() { //We use the callback function from fadein
var width = $(img).width();
var height = $(img).width();
});
This work around relies on that fadeIn will only execute the function after the image has been properly loaded. My issue was that I was emptying the div that contained the image and refilling it but it was still cached in the browser. So img.load() didn't do anything since it detected the image was indeed loaded.
From the jQuery documentation:
Can cease to fire for images that already live in the browser's cache
Hope this helps!
This may be a duplicate of Get the real width and height of an image with JavaScript? (in Safari/Chrome). There's a thorough write up over there.
Using $('img').css('width')
you get the value of width property of images's style not the actual image's width, use $('img').width()
instead.
精彩评论