javascript - 为什么我的 iframe 的文档宽度与 iframe 宽度相同?

标签 javascript css iframe width

我正在创建一个 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/

相关文章:

html - 无法让我的 css 选择器正常工作

python - selenium.common.exceptions.TimeoutException : this error will getting when I'm trying to button click using python

javascript - 如何通过iframe将php变量传递给javascript

css - 骨架子菜单文本

javascript - 如何使用 Jasmine 测试依赖注入(inject)的 Angular Controller ?

javascript - 克隆项目时,是否可以像这样更改所有输入属性和 ID?

javascript - 使用 .closest() 中的变量到选择器中

html - CSS Bootstrap : How to line up items?

javascript - 调整 &lt;iframe&gt; 的大小,以便整个内容按比例缩小或放大

javascript - OpenLayers 以米为单位绘制实际宽度的 LineString