考虑这段代码:
var img = new Image();
img.onload = function() {
console.log(this.width);
};
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/800px-Gull_portrait_ca_usa.jpg';
document.body.appendChild(img);
这将正确打印出图像宽度 (800)。但是如果我使用 CSS 应用最大宽度:
img {max-width: 400px}
测试用例:http://jsfiddle.net/MSjnM/
上面的 JS 代码将打印出 400
。这有点令人困惑,因为人们会认为 width
属性表示原始图像宽度,而不是计算出的宽度。
现在更令人困惑的是,如果我在宽度检测后将图像附加到 onload 事件中,我会得到不同的结果:
var img = new Image();
img.onload = function() {
console.log(this.width);
document.body.appendChild(img);
};
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/800px-Gull_portrait_ca_usa.jpg';
测试用例:http://jsfiddle.net/MSjnM/2/
这将打印出 800
,即使 CSS 已应用。我认为这是因为图像是在我检测到宽度之后附加的,并且一旦将图像插入到 DOM 中就会应用最大宽度。
好的,所以如果我想获得原始图像大小,无论何时或是否将 IMG
元素插入到 DOM 中,或者应用了任何 CSS 样式,我该怎么做都会失败-安全吗?
最佳答案
对我来说: 在 IE9、Opera、Safari(PC)、FF 和 chrome 中 naturalWidth/naturalHeight -properties 返回所需的值
关于javascript - 使用 maxWidth 时通过 JavaScript 检测图像宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9939668/