Html 代码作为 IFRAME 源而不是 URL [英] Html code as IFRAME source rather than a URL

查看:27
本文介绍了Html 代码作为 IFRAME 源而不是 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个 IFRAME 的标准代码,有没有办法用 html 代码替换 src URL?所以我的问题很简单,我有一个页面,它从 MYSQL 加载了一个 HTML 正文,我想在一个框架中呈现该代码,以便它独立于页面的其余部分并在该特定边框的范围内呈现它自己.

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>   

推荐答案

您可以使用数据 URL 执行此操作.这包括单个 HTML 字符串中的整个文档.例如,以下 HTML:

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>

可以这样编码:

data:text/html;charset=utf-8,%3Chtml%3E%3Cbody%3Efoo%3C/body%3E%3C/html%3E

然后设置为iframe的src属性.示例.

and then set as the src attribute of the iframe. Example.

另一种选择是使用 Javascript 执行此操作.这几乎可以肯定是我会选择的技术.您无法保证浏览器会接受多久的数据 URL.Javascript 技术看起来像这样:

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(2017 年 12 月):使用 Html5 的 srcdoc 属性,就像在 Saurabh Chandra Patel 的回答中一样,现在谁应该成为公认的答案!如果您可以有效地检测 IE/Edge,一个提示是使用 srcdoc-polyfill 库仅适用于它们以及所有非 IE/Edge 浏览器中的纯"srcdoc 属性(检查 caniuse.com 可以肯定).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆