我正在嘗試創建一個疊加層,它在單擊縮略圖時顯示較大版本的圖像。我遇到的問題是圖像的寬度被縮小到很遠。寬度比例計算正在應用兩次
我使用以下代碼:
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。
你誤調用函數兩次/ – cjds
有一姐「if」語句,將檢查,看看如果圖像的寬度比屏幕寬。我評論說,仍然有同樣的問題。 – Cedon
不是答案,但你可以簡化'this.height = this.height * this.ratio'到'this.height = window.innerHeight'。 –