javascript - 使用 maxWidth 时通过 JavaScript 检测图像宽度

标签 javascript jquery css image width

考虑这段代码:

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 返回所需的值

http://jsfiddle.net/MSjnM/5/

关于javascript - 使用 maxWidth 时通过 JavaScript 检测图像宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9939668/

相关文章:

javascript - 这两种执行方式有什么不同?

jquery - 自定义搜索 jQuery FancyTree 插件

java - GWT SimplePager - 为每个下一个和上一个添加历史记录

javascript - CSS 与 JavaScript 水平滑动/过渡

javascript - pdf制作: Use System Fonts

javascript - 使用jquery动态添加列表项到ul

javascript - 使用 getComputedStyle().getPropertyValue() 获取边框值? (莫斯拉,FF)

jquery 使用 select 中的值更改 attr href

javascript - jQuery 中样式小部件的应用似乎有所不同

html - 发现很难对齐登录界面