是否有一种可靠的、独立于框架的方法来确定<img src='xyz.jpg'>
客户端调整大小的物理尺寸?
确定图像跨浏览器的原始大小?
IT技术
javascript
image
2021-02-05 22:48:25
5个回答
您有 2 个选择:
选项1:
删除width
和height
属性并读取offsetWidth
和offsetHeight
选项 2:
创建一个 JavaScriptImage
对象,设置src
,然后读取width
和height
(您甚至不必将它添加到页面来执行此操作)。
function getImgSize(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
alert ('The image size is '+width+'*'+height);
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}
由 Pekka 编辑:正如评论中所同意的,我将函数更改为在图像的“onload”事件上运行。否则,大图像,height
而width
不会因为在拍摄时尚未加载任何回报。
图像(至少在 Firefox 上)具有naturalWidth
/height 属性,因此您可以使用它img.naturalWidth
来获取原始宽度
var img = document.getElementsByTagName("img")[0];
img.onload=function(){
console.log("Width",img.naturalWidth);
console.log("Height",img.naturalHeight);
}
您可以将图像预加载到 javascript Image 对象中,然后检查该对象的宽度和高度属性。
/* Function to return the DOM object's in crossbrowser style */
function widthCrossBrowser(element) {
/* element - DOM element */
/* For FireFox & IE */
if( element.width != undefined && element.width != '' && element.width != 0){
this.width = element.width;
}
/* For FireFox & IE */
else if(element.clientWidth != undefined && element.clientWidth != '' && element.clientWidth != 0){
this.width = element.clientWidth;
}
/* For Chrome * FireFox */
else if(element.naturalWidth != undefined && element.naturalWidth != '' && element.naturalWidth != 0){
this.width = element.naturalWidth;
}
/* For FireFox & IE */
else if(element.offsetWidth != undefined && element.offsetWidth != '' && element.offsetWidth != 0){
this.width = element.offsetWidth;
}
/*
console.info(' widthWidth width:', element.width);
console.info(' clntWidth clientWidth:', element.clientWidth);
console.info(' natWidth naturalWidth:', element.naturalWidth);
console.info(' offstWidth offsetWidth:',element.offsetWidth);
console.info(' parseInt(this.width):',parseInt(this.width));
*/
return parseInt(this.width);
}
var elementWidth = widthCrossBrowser(element);
只需稍微更改 Gabriel 的第二个选项,使其更易于使用:
function getImgSize(imgSrc, callback) {
var newImg = new Image();
newImg.onload = function () {
if (callback != undefined)
callback({width: newImg.width, height: newImg.height})
}
newImg.src = imgSrc;
}
网址:
<img id="_temp_circlePic" src="http://localhost/myimage.png"
style="width: 100%; height:100%">
示例调用:
getImgSize($("#_temp_circlePic").attr("src"), function (imgSize) {
// do what you want with the image's size.
var ratio = imgSize.height / $("#_temp_circlePic").height();
});