2015-09-17 81 views
1

我正在嘗試創建一個疊加層,它在單擊縮略圖時顯示較大版本的圖像。我遇到的問題是圖像的寬度被縮小到很遠。寬度比例計算正在應用兩次

我使用以下代碼:

largeImage.addEventListener('load', function() { 
    // Resize if Taller 
    if (this.height > window.innerHeight) { 
     this.ratio = window.innerHeight/this.height; 
     this.height = window.innerHeight; 
     this.width = this.width * this.ratio; 
     console.log('Ratio: ' + this.ratio); 
     console.log('Height: ' + this.height); 
     console.log('Width: ' + this.width); 
    } 

    // Resize if Wider 
    if (this.width > window.innerWidth) { 
     this.ratio = window.innerWidth/this.width; 
     this.height = this.height * this.ratio; 
     this.width = this.width * this.ratio; 
    } 
}, false); 

在考慮中的圖像是1000x1500和window.innerHeight和.innerWidth分別爲430px和1064px。 this.ratio計算出來0.2866666666666667,所以this.width應該計算爲287.但是我得到的是82,它是1000 * 0.2866666666666667 * 0.2866666666666667。

我放在console.log出於診斷的原因,this.height和this.ratio正在計算正確,但寬度乘以比例兩次莫名其妙。

編輯:我更新了代碼以包含整個eventHandler。

+1

你誤調用函數兩次/ – cjds

+0

有一姐「if」語句,將檢查,看看如果圖像的寬度比屏幕寬。我評論說,仍然有同樣的問題。 – Cedon

+0

不是答案,但你可以簡化'this.height = this.height * this.ratio'到'this.height = window.innerHeight'。 –

回答

2

的圖像的寬度當調整高度自動調整大小。

因此,您將高度調整爲0.2866666666666667(但這也會調整寬度),然後再次應用0.2866666666666667 - 這就是爲什麼您應用了兩次比率。

您可以註釋此行 - 你應該得到的值預計在控制檯:

this.width = this.width * this.ratio; 
+0

是的,我剛剛發現了這個代碼。現在我的問題是原始代碼的工作,因爲它實際上源於Lynda.Com課程(我曾通知作者)。所以我現在的問題是:什麼改變,使它自動做寬度以及?如何改變一個而不改變另一個? – Cedon

+0

如果寬度和高度例如在HTML中設置,那麼更改一個尺寸不會按比例調整另一個尺寸 - 只有在沒有預先設置寬度和高度時纔會發生這種情況。 – Daniel

+0

雖然在HTML中都沒有指定。這是一個全新的元素,由父級addEventListener通過點擊縮略圖來即時創建。 – Cedon

0

您需要提前計算新的高度和寬度值,以免因另一方的變化而產生偏斜。

function resize() { 
 
    var element = document.getElementById('image'); 
 
    var newHeight = element.height * 0.5; 
 
    var newWidth = element.width * 0.5; 
 
    
 
    console.log('Original width and height: ', element.width, element.height); 
 
    
 
    element.height = newHeight; 
 
    element.width = newWidth; 
 
    
 
    console.log('New width and height: ', element.width, element.height); 
 
}
<div> 
 
    <button onclick="resize()">Shrink By 50%</button> 
 
</div> 
 
<img id="image" src="https://www.gravatar.com/avatar/07bb1a01c672794db448fdb8e180042e?s=328&d=identicon&r=PG&f=1" />