无法使用 Javascript 在 Safari 中检索图像宽度,但在 Chrome 中工作正常

Can't retrieve image width in Safari using Javascript but works fine in Chrome

我有以下代码

img = document.getElementById('image'); // which is an <img> element

if (img.width > 0) {
    // I get here in Chrome, width is correct
} else {
    // I get here in Safari, width is 0
}

为什么 Safari 中的宽度 属性 为 0,我该如何解决?

您是否尝试读取 "offsetWidth" 对象。

img = document.getElementById('image');
img.offsetWidth // here you go

虽然这很重要,但请尝试使用 .clientWidth 而不是 .width

This answer 解释说

In the case of an IMG element, this will get the actual dimensions of the visible image.

HTML

<img id="image" width="0" height="100" src="http://placehold.it/100x100"/>

JavaScript

var img = document.getElementById('image'); // which is an <img> element

if (img.clientWidth > 0) {
    // I get here in Chrome, width is correct
    console.log('Do something if greater than 0')
} 
else {
    // I get here in Safari, width is 0
    console.log('Do something else if not greater than 0')
}

这里有一个快速 Codepen link 来展示它在两种浏览器中的工作情况

Safari 可能无法访问图像的尺寸,因此在您探测图像时无法计算其宽度和高度。

您应该等待图像加载,这会触发一个事件处理程序,您可以从中获取图像尺寸。