指定页面的 iframe 内容,而不是 src 属性

我目前正在工作的形式,其中包括一些文件输入上传图片。对于这些输入,有一个 onchange()事件,它将图片提交给 iframe,然后将上传的图片动态加载到表单中,并为其修改字段(如 姓名地理定位)。

因为我不能嵌套表单,所以 file_input也包含在 iframe中。最后,我使用一个 iframe内的另一个 iframe。所以我有这样的东西:

<form>
<!-- LOTS OF FIELDS!! -->
<iframe src="file_input_url">
<!-- iframe which loads a page of a form with a file input-->
</iframe>
</form>

加载到 iframe中的 HTML 类似于(不包括 htmlheadbody标记)

<form target="upload_iframe">
<input type="file" onchange="this.form.submit()">
</form>
<iframe name="upload_iframe"></iframe>

除了加载第一个 iframe需要几秒钟这个事实之外,这种方法非常有效,因此文件输入不会随页面的其余部分一起加载。这在视觉上并不理想。我可以解决它,如果我可以指定的 iframe内容,而不需要加载另一个页面(指定的 file_input_url在第一个 iframe)。

是否有方法在同一文档中指定 iframe内容,或者只能用 src属性指定,这需要加载另一个页面?

139773 次浏览

You can .write() the content into the iframe document. Example:

<iframe id="FileFrame" src="about:blank"></iframe>


<script type="text/javascript">
var doc = document.getElementById('FileFrame').contentWindow.document;
doc.open();
doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
doc.close();
</script>

In combination with what Guffa described, you could use the technique described in Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.

iframe now supports srcdoc which can be used to specify the HTML content of the page to show in the inline frame.

You can use data: URL in the src:

var html = 'Hello from <img src="http://stackoverflow.com/favicon.ico" alt="SO">';
var iframe = document.querySelector('iframe');
iframe.src = 'data:text/html,' + encodeURIComponent(html);
<iframe></iframe>

Difference between srcdoc=“…” and src=“data:text/html,…” in an iframe.

Convert HTML to data:text/html link using JavaScript.