2011-01-06 81 views
0


我想創建一個非常簡單的圖庫使用JavaScript。有縮略圖,當它們被點擊時,大圖片的來源得到更新。一切工作正常,除了當我在IE中嘗試它的圖像的大小保持與原始圖像的大小相同。假設初始圖像是200x200,然後點擊100x100圖像的縮略圖,圖像即會顯示,但會被拉伸至200x200。我沒有設置任何寬度或高度值,所以我猜瀏覽器應該使用圖像的正常大小,例如FF。改變圖像的大小不同的圖像的源,將不會在IE中調整大小

這裏的一些代碼:

function showBigImage(link) 
{ 
var source = link.getAttribute("href"); 
var bigImage = document.getElementById("bigImage"); 
bigImage.setAttribute("src", source); 
return false; /* prevent normal behaviour of <a> element when clicked */ 
} 

和HTML看起來像這樣:

<ul id="gallery"> 
<li> 
    <a href="images/gallery/1.jpg"> 
    <img src="images/gallery/1thumb.jpg"> 
    </a> 
</li> 
    (more <li> elements ...) 
</ul> 

大的圖像是動態創建的:

function createBigImage() 
{ 
var bigImage = document.createElement("img"); 
bigImage.setAttribute("id", "bigImage"); 
bigImage.setAttribute("src", "images/gallery/1.jpg"); 

var gal = document.getElementById("gallery"); 
var gal_parent = gal.parentNode; 
gal_parent.insertBefore(bigImage, gal); 
} 

還有一些代碼設置的onclick事件在鏈接上,但我認爲它不適用於這個網站。正如我所說的問題只與IE瀏覽器。提前致謝!

回答

0

IE的聲音在創建時計算widthheight屬性爲#bigImage,然後在更改src時未更新它們。其他瀏覽器可能注意到他們必須自己計算圖像尺寸,以便在更改src時重新計算它們。這兩種方法都足夠合理。

您知道showBigImage()照片的大小嗎?如果你這樣做,然後設置widthheight當您更改src明確屬性:

function showBigImage(link) { 
    var source = link.getAttribute("href"); 
    var bigImage = document.getElementById("bigImage"); 
    bigImage.setAttribute("src", source); 
    bigImage.setAttribute("width", the_proper_width); 
    bigImage.setAttribute("height", the_proper_height); 
    return false; 
} 

如果你不知道新的維度,然後更改showBigImage()刪除#bigImage並創建一個新:

function createBigImage(src) { 
    var bigImage = document.createElement("img"); 
    bigImage.setAttribute("id", "bigImage"); 
    bigImage.setAttribute("src", src || "images/gallery/1.jpg"); 

    var gal = document.getElementById("gallery"); 
    gal.parentNode.insertBefore(bigImage, gal); 
} 

function showBigImage(link) { 
    var bigImage = document.getElementById("bigImage"); 
    if(bigImage) 
     bigImage.parentNode.removeChild(bigImage); 
    createBigImage(link.getAttribute("href");); 
    return false; 
}