如何更改 iframe 内图像的样式

问题描述

我用 Vaadin 7 生成一个 iframe,结果是:

<div class="zoom-to-fit" style="width: 1200px; height: 900px;">
    <iframe src="http://localhost:8090/image.png" frameborder="0" width="100%" height="100%">
    </iframe>
</div>

我可以向 iframe 添加样式类 zoom-to-fit,但 iframe 被包裹在一个 div 中。

我正在尝试将图像拉伸到 iframe,但它不起作用。

我尝试了以下方法

.zoom-to-fit {
    width: 100%;
    height: 100%;
}
.zoom-to-fit {
    background-size: 100% 100%;
}
.zoom-to-fit > html > body > img {
    width: 100%;
    height: 100%;
}

但它们不起作用。

添加了最后一个,因为开发者工具中的 html 代码如下所示:

enter image description here

我想我无法修改 iframe 中的任何样式...但是我如何调整图像大小?

我知道如果我转到图像并添加一个样式(宽度和高度为 100% 有效),但我只能使用我正在使用的 Vaadin 框架添加删除样式。

解决方法

我从一个可能有帮助的论坛帖子中看到了这一点: https://vaadin.com/forum/thread/393458/embedded-component-image-and-setwidth-resizing-both-component-and-image

还有这个来自另一个SO问题: Resizing Vaadin Image

,

因此,无法通过 css 更改样式,因此解决方案有点讨厌(或不是很好)。

CSS 不知道 iframe 内部的结构,所以它没有按照我想要的方式应用。但由于 bot 网站和 iframe 的内容来自同一来源,javascript 可以安全使用(也是使其工作的唯一方法)。

幸运的是,vaadin 中有一个工具可以安全地执行 javascript。所以我可以得到 iframe 标签,然后是 img 标签。

import com.vaadin.ui.JavaScript;

JavaScript.getCurrent().execute(
    "document.getElementsByTagName('iframe')[1].contentDocument.body.children[0].style=" 
    + "'width: 100%; height: 100%;'");

这是普通的 javascript,所以它应该适用于大多数浏览器。