簡體   English   中英

無法為iframe調用null的方法“ appendChild”

[英]Cannot call method 'appendChild' of null for iframes

我有以下腳本來創建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控制台中,它給我錯誤無法調用null的方法'appendChild'

為什么它不起作用?

代碼正確。 您在頁面中添加了正文嗎?

嘗試這個:

<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不是最干凈的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM