Home >Web Front-end >JS Tutorial >How to Get the True Dimensions of an Image in Safari and Chrome?
Getting the True Dimensions of an Image in Safari and Chrome
When crafting a jQuery plugin, extracting the actual width and height of an image is crucial. However, using the standard "width()" and "height()" methods yields zero values in WebKit browsers like Safari and Chrome.
To resolve this issue, leveraging an image's "onload" event is recommended instead of timeouts. This technique involves creating an in-memory copy of the image to avoid CSS interference.
var img = $("img")[0]; // Get my img elem var pic_real_width, pic_real_height; $("<img/>") // Make in memory copy of image to avoid css issues .attr("src", $(img).attr("src")) .load(function() { pic_real_width = this.width; // Note: $(this).width() will not pic_real_height = this.height; // work for in memory images. });
Alternatively, HTML5's "naturalHeight" and "naturalWidth" attributes can also be utilized.
The above is the detailed content of How to Get the True Dimensions of an Image in Safari and Chrome?. For more information, please follow other related articles on the PHP Chinese website!