我试图将 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>
这是我的结果的屏幕截图 -
如您所见,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/