2010-10-14 273 views
0

我想推遲使用普通JS的圖像加載。我的方法是通過爲圖像提供空的src字段並將圖像url插入到名爲「lang」的臨時屬性中,如下例所示。即> <img lang="logo.gif">而不是<img src="logo.gif">。當按下按鈕時,下面的js被啓動,以將虛擬「lang」屬性的值插入到src中。Javascript延遲圖像加載

function showimagesunderdiv(divid) 
{ 
tr = document.getElementById(divid); 
pics=tr.getElementsByTagName('img'); 
for(i=0;i<pics.length;i++) 
    { 
    if(pics[i].lang) 
    { 
    pics[i].src=pics[i].lang; 
    pics[i].style.display=''; 
    } 
    } 
} 

雖然這個工程是鉻和FF,IE是做問題。任何想法?

+0

嘗試使用圖片[i]中。的style.display = '塊';而不是圖片[i] .style.display =''; – lock 2010-10-14 23:09:53

+0

你有什麼問題?我複製了你的代碼,並在IE7,IE8和IE9中運行,沒有任何問題。 – gilly3 2010-10-14 23:17:33

+0

「做問題」? – titaniumdecoy 2010-10-14 23:24:00

回答

1

也許這:

<html> 
<body> 
<p>Images:</p> 
<img name=image0> 
<img name=image1> 
<img name=image2> 
<img name=image3> 
End of document body. 
</body> 
<script type="text/javascript"> 
function LoadImage(imageName,imageFile) 
{ 
    if (!document.images) return; 
    document.images[imageName].src = imageFile'; 
} 
LoadImage('image4','number4.gif'); 
LoadImage('image5','number5.gif'); 
LoadImage('image6','number6.gif'); 
LoadImage('image7','number7.gif'); 
</script> 
</html> 

或者這樣:

<html> 
<body> 
<p>Images:</p> 
<img name=image0 onLoad="LoadImage('image1','number1.gif')"> 
<img name=image1 onLoad="LoadImage('image2','number2.gif')"> 
<img name=image2 onLoad="LoadImage('image3','number3.gif')"> 
<img name=image3> 
End of document body. 
</body> 
<script type="text/javascript"> 
var loadingImage = false; 
function LoadImage(imageName,imageFile) 
{ 
    if ((!document.images) || loadingImage) return; 
    loadingImage = true; 
    if (document.images[imageName].src.indexOf(imageFile)<0) 
    { 
    document.images[imageName].src = imageFile; 
    } 
    loadingImage = false; 
} 
LoadImage('image0','number0.gif'); 
</script> 
</html> 

我知道這是不是你的代碼的修正,但我不能看到什麼錯......

這是一個非常兼容的方案!

希望它有幫助!資源:

http://www.cryer.co.uk/resources/javascript/script3.htm

0

給每個圖像標記的ID,這些ID和URL存儲在數組中:

imagesToLoad = [["imgId1", "http://..."], ["imgId2", "..."], ...]; 

及用途:

function showimages(imageList) 
{ 
    for(var x = 0; x < imageList.length; x++) { 
    document.getElementById(imageList[x][0]).src = imageList[x][1]; 
    } 
} 

showImages(imagesToLoad);