javascript - 在检查器窗口和 JavaScript 中看到的 img 标签尺寸之间的区别

标签 javascript html

我试图将 img 标签的尺寸发布到 php 文件,然后我发现检查器指定的尺寸与 Javascript 和 JQuery 函数返回的尺寸不同。

这里我给出的 HTML 代码只包含必要的 Material 而不是整个代码 -

<!doctype html>
 <html>
   <head>
     <style>
        img{
            max-width : 600px;
            max-height: 600px;
        }
     </style>
   </head>
   <body>
     <img id="photo" src="milky_way.jpg">
     <script>   
         document.write(
            "<br/>Dimensions returned by Javascript : <br/>"+
            "Width : "+document.getElementById("photo").width+
            "Height : "+document.getElementById("photo").height
            );
     </script>

   </body>
 </html>

这是我的结果的屏幕截图 -

enter image description here

如您所见,javascript 代码将宽度和高度返回为 - 分别为 600 和 338 而当通过检查器窗口检查尺寸时,它是 - 分别为 720 和 405。

此外,图像的原始尺寸为 - 1920 x 1080。
为什么会有这样的差异?

最佳答案

你看到的width/height就是你看到的实际值。

如果您想获取图像的原始宽度/高度,您可以创建一个新的 img 对象,并从该对象获取值(加载):

document.write(
  "<br/>Dimensions returned by Javascript : <br/>"+
  " Width : "+document.getElementById("photo").width+
  " Height : "+document.getElementById("photo").height
);
var img = new Image()
img.src = document.getElementById("photo").getAttribute('src')
img.onload = function() {
  document.getElementById('result').innerHTML = "<br/>Original Dimensions : <br/>"+
  " Width : "+this.width+
  " Height : "+this.height
}
img{
            max-width : 600px;
            max-height: 600px;
        }
<img id="photo" src="https://dummyimage.com/1920x1080/000/fff">
<div id="result"></div>

In your screenshot - Firefox show the actual width/height an element is taking on the screen (and if you are in zoomin/zoomout - it will take that zoom into account). This is not the behavior in Chrome, for example. Chrome will ignore the zoom-effect.

You can set default zooming (using CTRL+0) and check again.

关于javascript - 在检查器窗口和 JavaScript 中看到的 img 标签尺寸之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41379273/

相关文章:

javascript - 简单的 add 函数返回 NaN

javascript - 在白色背景 div 下推送页脚

html - 网页设计中的硬编码 "width"是否可以接受?

javascript - onClick 影响另一个元素但相同的 react 组件

javascript - 如何在表格中隐藏/显示 tr 标签而不更改单元格的宽度和排序

javascript - NodeJS 正则表达式匹配字符串中的 4 位数字与 'OR' 字

javascript - 使用 javascript 检查字符串中是否包含单词/字母

python - 使用 Flask 链接到网站内的另一个页面

html - 类似 Bootstrap 的网格中的 CSS 偏移

javascript - 切换图像在 jquery 中不起作用