HTML代码作为IFRAME源代码而不是URL [英] Html code as IFRAME source rather than a URL
问题描述
这个IFRAME的标准代码是否有一种方法可以用Just html代码替换src URL?所以我的问题很简单,我有一个从MYSQL加载HTML主体的页面我想在框架中呈现该代码,以便使其自身独立于页面的其余部分以及该边界的边界。
< iframe src =http://example.comname =testheight =120width =600 >您需要支持Frames的浏览器才能查看此内容。< / iframe>
您可以使用数据网址来完成此操作。这包括整个文档在一个单一的HTML字符串中。例如,以下HTML:
< html>< body> foo< / body>< / html>
可以编码为:
data:text / html; charset = utf-8,%3Chtml%3E%3Cbody%3Efoo%3C / body%3E%3C / html%3E
,然后设置为iframe的 src
属性。 示例。
编辑:另一种选择是用Javascript来做到这一点。这几乎可以肯定是我选择的技术。您无法保证浏览器接受数据网址的时间。 Javascript技术看起来像这样:
var iframe = document.getElementById('foo'),
iframedoc = iframe.contentDocument || iframe.contentWindow.document;
iframedoc.body.innerHTML ='Hello world';
:使用 Html5的 srcdoc 属性,就像在 Saurabh Chandra Patel 的答案中一样,现在他应该成为公认的答案!如果您可以高效检测IE / Edge ,则小窍门是使用 srcdoc-polyfill 库以及所有非IE / Edge浏览器中的纯srcdoc属性(选中 caniuse.com )。 <$ p $ < / body>< / html>>< / html>< body>您好,< b>世界< / b><的iframe>
This standard code for an IFRAME, is there a way to replace the src URL with Just html code? so my problem is simple, I have a page it loads an HTML body from MYSQL I want to present that code in a frame so it renders it self independent of the rest of the page and in the confines of that specific bordering.
<iframe src="http://example.com" name="test" height="120" width="600">You need a Frames Capable browser to view this content.</iframe>
You can do this with a data URL. This includes the entire document in a single string of HTML. For example, the following HTML:
<html><body>foo</body></html>
can be encoded as this:
data:text/html;charset=utf-8,%3Chtml%3E%3Cbody%3Efoo%3C/body%3E%3C/html%3E
and then set as the src
attribute of the iframe. Example.
Edit: The other alternative is to do this with Javascript. This is almost certainly the technique I'd choose. You can't guarantee how long a data URL the browser will accept. The Javascript technique would look something like this:
var iframe = document.getElementById('foo'),
iframedoc = iframe.contentDocument || iframe.contentWindow.document;
iframedoc.body.innerHTML = 'Hello world';
Edit 2 (December 2017): use the Html5's srcdoc attribute, just like in Saurabh Chandra Patel's answer, who now should be the accepted answer! If you can detect IE/Edge efficiently, a tip is to use srcdoc-polyfill library only for them and the "pure" srcdoc attribute in all non-IE/Edge browsers (check caniuse.com to be sure).
<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>
这篇关于HTML代码作为IFRAME源代码而不是URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!