我正在尝试创建一个叠加层,在单击缩略图时显示更大版本的图像。我遇到的问题是图像的宽度被缩小到很远。
我正在使用以下代码:
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。
最佳答案
当您调整高度时,图像的宽度会自动调整。
因此,您将高度调整为 0.2866666666666667(但这也会调整宽度),然后再次应用 0.2866666666666667 - 这就是为什么您会应用两次比率。
您可以评论这一行 - 您应该在控制台中获得预期的值:
this.width = this.width * this.ratio;
关于javascript - 宽度比计算被应用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32638275/