我有一个输入文本字段,用户在其中提供图像的源网址,
例如 http://mysite/images/STARTPAGE_LOGO.gif
是一个有效值。
我的 html 文档中没有任何 img
标记或其他内容。我如何确定用户输入的 URL 中显示的图像的尺寸。
最佳答案
没有方法可以在不加载图像的情况下找出图像的宽度和高度,因此您必须动态加载它,为此您可以使用
function getDimensions(_src,_callback){
/* create a new image , not linked anywhere in document */
var img = document.createElement('img');
/* set the source of the image to what u want */
img.src=_src;
/* Wait the image to load and when its so call the callback function */
/* If you want the actual natural dimensions of the image use naturalWidth and natural height instead */
img.onload = function () { _callback(img.width,img.height) };
}
以纯 JavaScript 精神声明上述函数后,您可以执行类似的操作
getDimensions('http://mysite/images/STARTPAGE_LOGO.gif',function(w,h){
console.log( "Height : ",h,"Width:",w);
});
关于javascript - 如何通过url知道图片的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11934802/