无法为iframe调用null的方法'appendChild'

时间:2013-04-20 08:18:03

标签: javascript google-chrome

我有以下脚本来创建iframe

  function createIframe() {
    var iframe = document.createElement("iframe");
    iframe.style.position = "absolute";
    iframe.style.visibility = "hidden";

    document.body.appendChild(iframe);

    // Firefox, Opera
    if(iframe.contentDocument) iframe.doc = iframe.contentDocument;
    // Internet Explorer
    else if(iframe.contentWindow) iframe.doc = iframe.contentWindow.document;

    // Magic: Force creation of the body (which is null by default in IE).
    // Also force the styles of visited/not-visted links.
    iframe.doc.open();
    iframe.doc.write('<style>');
    iframe.doc.write("a{color: #000000; display:none;}");   
    iframe.doc.write("a:visited {color: #FF0000; display:inline;}");    
    iframe.doc.write('</style>');
    iframe.doc.close();

    // Return the iframe: iframe.doc contains the iframe.
    return iframe;
  }  

然而在Chrome控制台中它给我错误无法调用方法'appendChild'为null

为什么不起作用?

1 个答案:

答案 0 :(得分:0)

代码是正确的。你有没有在页面中添加正文?

试试这个:

<html>
<body>
<script>
window.onload=function() {
   createIframe()
};
function createIframe() {
    var iframe = document.createElement("iframe");
    iframe.style.position = "absolute";
    iframe.style.visibility = "hidden";

    document.body.appendChild(iframe);

    // Firefox, Opera
    if(iframe.contentDocument) iframe.doc = iframe.contentDocument;
    // Internet Explorer
    else if(iframe.contentWindow) iframe.doc = iframe.contentWindow.document;

    // Magic: Force creation of the body (which is null by default in IE).
    // Also force the styles of visited/not-visted links.
    iframe.doc.open();
    iframe.doc.write('<style>');
    iframe.doc.write("a{color: #000000; display:none;}");   
    iframe.doc.write("a:visited {color: #FF0000; display:inline;}");    
    iframe.doc.write('</style>');
    iframe.doc.close();

    // Return the iframe: iframe.doc contains the iframe.
    return iframe;
  }  
</script>
</body>
</html>

iframe.doc.write不是最干净的解决方案......