我正在创建一个 iframe,如下所示:
<!doctype html><html><head></head><body>
<iframe src="file:///C:/Users/DD/Desktop/myiframe.html" width=200 height=200 scrolling="no" frameborder=0></iframe>
</body></html>
在 iframe 内部,我试图找到可能小于 iframe 大小的内容大小,但我无法获得宽度来报告任何小于 iframe 创建的 200 像素大小的内容作为。
<!doctype html><html><head></head>
<body style="margin:0px;border:0px;padding:0px;font-size:0px;">
<img id="myimg" width=75 height=50>
<script>
var body = document.body, html = document.documentElement;
function consoleNow() {
console.log("body.scrollWidth x Height = " +body.scrollWidth+" x "+body.scrollHeight);
console.log("body.offsetWidth x Height = " +body.offsetWidth+" x "+body.offsetHeight);
console.log("html.scrollWidth x Height = " +html.scrollWidth+" x "+html.scrollHeight);
console.log("html.offsetWidth x Height = " +html.offsetWidth+" x "+html.offsetHeight);
console.log("body.offsetWidth x Height = " +body.offsetWidth+" x "+body.offsetHeight);
console.log("html.clientWidth x Height = " +html.clientWidth+" x "+html.clientHeight);
console.log("-----------------");
}
consoleNow();
function increaseSize() {
document.getElementById("myimg").style.width = "150px";
document.getElementById("myimg").style.height = "100px";
consoleNow();
}
setTimeout(increaseSize,2000);
</script></body></html>
Here are the console outputs with before image resize and after:
body.scrollWidth x Height = 200 x 50
body.offsetWidth x Height = 200 x 50
html.scrollWidth x Height = 200 x 200
html.offsetWidth x Height = 200 x 50
body.offsetWidth x Height = 200 x 50
html.clientWidth x Height = 200 x 200
-----------------
body.scrollWidth x Height = 200 x 100
body.offsetWidth x Height = 200 x 100
html.scrollWidth x Height = 200 x 200
html.offsetWidth x Height = 200 x 100
body.offsetWidth x Height = 200 x 100
html.clientWidth x Height = 200 x 200
-----------------
在那个 iframe 中,我最初将内容(图像)的大小设置为 75x50,但所有已知/推荐的方法都报告宽度为 200。2 秒后,我将图像的大小更改为 150x100,但仍然得到错误的宽度.说到高度,我得到了很好的数据。
我希望答案是应用于主体的 CSS 属性,但我不确定它会是什么。
最佳答案
body
的 CSS width
属性是 auto
(默认值),因此它会占用尽可能多的空间。由于 overflow
设置为 hidden
,因此如果子元素更宽,它不会超出该范围。
可用空间是包含文档的框架的宽度。
如果你想测量 body 内部某物的宽度,那就测量那个东西的宽度。
关于javascript - 为什么我的 iframe 的文档宽度与 iframe 宽度相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57590918/