2011-12-26 57 views
2

我想要讀取由for-loop中的url指定的圖像的寬度(orgWidth),計算其高度爲480px的新寬度(calcWidth)。獲取由URL指定的圖像的寬度jquery

for (var i=1; i <= item.length; i++) { 

    url = document.images[i].rsc; 
    orgWidth = some-fancy-thing-that-reads-the-width; 
    orgHeight = some-fancy-thing-that-reads-the-height; 

    factor = orgHeight/480  // 1400/480 = 2.916 
    calcWidth = orgWidth/factor  // 1000/2.916 = 342.935 

    document.images[i].width = calcWidth; 

} 

頁我需要它: http://foto.hendrik-schicke.de/index.php/people

+0

你可能想看看http://stackoverflow.com/questions/1643858/image-native-width-in-jquery – 2011-12-26 15:06:24

回答

3

這是不可能的使用JavaScript,那肯定是不可能的「不預載的」任意,因爲你需要「有」的文件中爲了做一些事情。

你最好的辦法是將圖像的URL傳遞給服務器端腳本(PHP?),它將獲取圖像尺寸並將數據傳回給您或將其存儲在數據庫中(可能性無窮無盡)。

但要回答你的問題,這是不可能的純JavaScript沒有加載圖像。

+0

是否有辦法要做到預加載,但要聲稱的功能? – Kibou 2011-12-26 15:18:35

+0

是的,如果你預載圖像:http://stackoverflow.com/q/623172/158014 – Jakub 2011-12-26 15:22:26

7
var tmpImg = new Image(); 
tmpImg.src="https://www.google.com/intl/en_com/images/srpr/logo3w.png"; //or document.images[i].src; 
$(tmpImg).on('load',function(){ 
    var orgWidth = tmpImg.width; 
    var orgHeight = tmpImg.height; 
    alert(orgWidth+"x"+orgHeight); 
}); 

演示:http://jsfiddle.net/eWzWg/3/

+0

你的演示和我的頁面返回0 orgWidth和orgHeight。 :( – Kibou 2011-12-26 15:35:01

+0

看起來圖像加載需要時間,請嘗試編輯的答案,http://jsfiddle.net/eWzWg/3/ – Usman 2011-12-26 15:39:17

+0

適用於本示例,但不適用於我的頁面。for循環完成部分「$ (tmpImg).one('load',function(){「開始。 請參閱:http://jsfiddle.net/eWzWg/10/ – Kibou 2011-12-26 16:05:46

3

我們可以檢查圖像是否已經被加載到瀏覽器的緩存。只有在加載圖像時,我們將onload處理程序綁定到它。這是純粹的JavaScript例子。

var image; 
function onload() { 
    console.log(image.height, image.width); 
} 

image= new Image(); 
image.src="https://www.google.com/intl/en_com/images/srpr/logo3w.png"; 
// check if image is already loaded to cache 
if (image.complete) { 
    console.log('image already loaded to browser'); 
    onload(); 
} else { 
    // or bind onload handler for image 
    image.onload = onload; 
} 

播放與例如在jsFiddle