我想将iframe元素添加到页面,然后<p>在iframe中添加元素.
我试过这个:
var iframe = document.createElement('iframe');
iframe.frameBorder = 1;
iframe.width = "500px";
iframe.height = "250px";
iframe.id = "iframe";
var p = document.createElement('p');
iframe.appendChild(p);
document.getElementById("div").appendChild(iframe); //this is a div that I have in body.
Run Code Online (Sandbox Code Playgroud)
iframe已添加到页面中,但P未添加到iframe(iframe的正文)中
在现代浏览器中,您使用contentDocument属性.在其他情况下,您必须使用contentWindow.document.您可以在onload事件中使用iframe的文档创建段落.所以:
var iframe = document.createElement('iframe');
iframe.frameBorder = 1;
iframe.width = "500px";
iframe.height = "250px";
iframe.id = "iframe";
iframe.onload = function()
{
var doc = iframe.contentDocument || iframe.contentWindow.document;
var p = doc.createElement('p');
p.textContent = "Paragraph in iframe";
doc.body.appendChild(p);
};
document.getElementById("div").appendChild(iframe); //this is a div that I have in body.
Run Code Online (Sandbox Code Playgroud)
我做了一个jsfiddle演示.
另外,我建议您不要使用与标记名称相同的ID.它可能会变得令人困惑.
| 归档时间: |
|
| 查看次数: |
12190 次 |
| 最近记录: |