简体   繁体   English

使用JavaScript获取图像的实际宽度和显示宽度

[英]Get both the real and shown width of an image using JavaScript

I have several images in an HTML document. 我在HTML文档中有几个图像。 The width of those elements is often modified due to a max-width CSS property that is applied to all of them. 由于应用于所有元素的max-width CSS属性,通常会修改这些元素max-width

I want to know whether it is possible to get both the real width of the .jpeg/.png/.whatever image files and the width that is being shown to the user, this is, I want to be able to know whether the images are being resized due to the max-width property or not. 我想知道是否有可能获得.jpeg / .png / .whatever图像文件的实际宽度和向用户显示的宽度,这是,我希望能够知道图像是否由于max-width属性而被调整大小。

Resizing the images with JavaScript after the page has loaded instead of using max-width is not acceptable. 在页面加载后使用JavaScript调整图像大小而不是使用max-width是不可接受的。

答案(刚刚删除它的人指出)是使用naturalWidth

 window.addEventListener("load", function() { var imgs = document.querySelectorAll('img'); for (var i = 0; i < imgs.length; i++) { var imgTag = imgs[i]; var image = new Image(); image.src = imgTag.src; output.innerHTML = "Width: " + image.width + " Height: " + image.height; } }); 
 img { max-width: 200px; } 
 <img src="http://www.google.com/images/srpr/logo11w.png"/> <p id="output"></p> 

I just put this together, and it seemed to work. 我把它放在一起,它似乎工作。

It depends on the JavaScript Image type. 这取决于JavaScript Image类型。 I also used "onload" rather than DOMContentLoaded, so that when querying about the image, we can be certain that it's already been loaded and doesn't need to wait for its onLoad callback. 我还使用了“onload”而不是DOMContentLoaded,因此在查询图像时,我们可以确定它已经被加载并且不需要等待它的onLoad回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM