0

我有以下脚本来创建 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 控制台中,它给了我错误 Cannot call method 'appendChild' of null

为什么它不工作?

4

1 回答 1

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 不是最干净的解决方案....

于 2013-04-20T08:25:00.620 回答