In the realm of Javascript image manipulation, obtaining the true width and height of an image can pose challenges, particularly in Webkit browsers like Safari and Chrome.
When utilizing jQuery in Firefox 3, IE7, and Opera 9, the following code snippet effectively extracts the actual image dimensions:
var pic = $("img"); pic.removeAttr("width"); pic.removeAttr("height"); var pic_real_width = pic.width(); var pic_real_height = pic.height();
However, in Webkit browsers, this approach yields incorrect values of 0.
The solution lies in tapping into the onload event of the image element. The modified code below accomplishes this:
var img = $("img")[0]; // Get the image element $("<img/>") // Make a virtual copy of the image to prevent CSS interference .attr("src", $(img).attr("src")) .load(function() { pic_real_width = this.width; pic_real_height = this.height; });
By creating a memory copy of the image and utilizing the this keyword within the load event, we bypass any potential CSS effects that could alter the image's dimensions.
For compatibility with HTML5 browsers, you can also leverage the naturalHeight and naturalWidth attributes:
var pic_real_width = img.naturalWidth; var pic_real_height = img.naturalHeight;
The above is the detailed content of How to Accurately Retrieve Image Dimensions in WebKit Browsers (Safari and Chrome)?. For more information, please follow other related articles on the PHP Chinese website!