閱讀539 返回首頁    go iPhone_iPad_Mac_apple


JS操作未跨域iframe裏的DOM

這裏簡單說明兩個方法,都是未跨域情況下在index.html內操作b.html內的 DOM。

如:index.html內引入iframe,在index內如何用JS操作iframe內的DOM元素?

先貼下index.html和iframe引入的a.html內容。

index->

<div class="d1">
        <iframe src="a.html" frameborder="0" name="one" id="iframeId"></iframe>
    </div>

a.html

<div id="dd">
        <h1>iframe裏的元素!</h1>
    </div>

 

法一:

var d=window.frames["one"].window;
    d.onload=function(){
        console.log(d.document.getElementById("dd"));
    };

法二:

JS動態創建iframe並插入

複製代碼
var ifr = document.createElement('iframe');
    ifr.src = 'a.html';
    document.body.appendChild(ifr);
    ifr.onload = function(){
        var doc = ifr.contentDocument || ifr.contentWindow.document;
        // 在這裏操縱b.html
        console.log(doc.getElementById("dd"));
    };
複製代碼

兩種的輸出結果都是

最後更新:2017-11-05 11:35:36

  上一篇:go  CSS3D效果
  下一篇:go  js中的彈框