我有一个输入文本字段,其中用户提供图像的源URL,例如 http://mysite/images/STARTPAGE_LOGO.gif
是一个有效值。如何通过它知道图像的大小url
我没有任何img
标记或在我的HTML文档中的其他东西。我如何确定用户输入的URL的图像尺寸。
我有一个输入文本字段,其中用户提供图像的源URL,例如 http://mysite/images/STARTPAGE_LOGO.gif
是一个有效值。如何通过它知道图像的大小url
我没有任何img
标记或在我的HTML文档中的其他东西。我如何确定用户输入的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);
});
HTML:
<input id="src" type="text" value="https://www.google.pl/images/srpr/logo3w.png"/>
JAVASCRIPT:上onload事件
var img = new Image; // create tmp image element
// is equal to document.createElement('img');
绑定函数,它会被自动加载图像时调用。
img.onload = function(){
alert(this.width +" : " + this.height);
};
设置图像的来源;
img.src = document.getElementById('src').value // get the value of input element;
出于好奇jQuery中:
$('<img/>').attr('src',$('#src').val()).bind('load',function(){
alert(this.width +' x ' + this.height);
});
任何理由downvote :) – abuduba 2012-08-13 13:10:13
的jQuery这样简单的东西是矫枉过正 – ShrekOverflow 2012-08-13 13:11:27
exaxctly他说什么^ – gonchuki 2012-08-13 13:12:05
'size'是指以字节为单位的大小还是像宽度和高度这样的图像属性? – 2012-08-13 13:05:30
他意味着宽度和高度 – ShrekOverflow 2012-08-13 13:07:32
您将不得不动态加载它。这里的答案说明如何?http://stackoverflow.com/questions/1310378/determining-image-file-size-dimensions-via-javascript – 2012-08-13 13:07:42