Determining Image Dimensions in Webkit Browsers
When developing JavaScript plugins, obtaining the actual width and height of an image is crucial. While conventional methods work in Firefox, IE, and Opera, they fail in Safari and Chrome, where the returned values are zero.
WebKit's Unique Image Loading Behavior
Unlike other browsers, Webkit sets the height and width properties of an image only after it has been loaded. This behavior requires a different approach to retrieving the true image dimensions.
利用图片加载事件
The recommended solution involves using an image's onload event. Below is a modified code snippet that resolves the issue:
var img = $("img")[0]; // Get the image element var pic_real_width, pic_real_height; $("<img/>") // Create an in-memory copy to avoid CSS issues .attr("src", $(img).attr("src")) .load(function() { pic_real_width = this.width; pic_real_height = this.height; });
Avoiding CSS Effects
To prevent CSS effects from affecting the dimensions, the code creates an in-memory copy of the image. This technique ensures that the retrieved values accurately reflect the actual image size.
Alternative Approach: HTML5 Attributes
HTML5 provides the naturalHeight and naturalWidth attributes, which can also be used to retrieve the real image dimensions. However, support for these attributes varies across browsers.
The above is the detailed content of How to Reliably Get Image Dimensions in WebKit Browsers?. For more information, please follow other related articles on the PHP Chinese website!