色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

js跨域問題之跨域iframe自適應(yīng)大小實(shí)現(xiàn)代碼

復(fù)制代碼 代碼如下:
<body onload="Javascript: setHeight();">
<script>
function setHeight(){
var dHeight = document.documentElement.scrollHeight;
var t = document.createElement("div");
t.innerHTML = '<iframe id="kxiframeagent" src="http://rest.kaixin001.com/api/agent.html#'+dHeight+'"scrolling="yes" height="0px" width="0px"></iframe>';
document.documentElement.appendChild(t.firstChild);
}
</script>

我想著跨域如何解決啊!后來(lái)去網(wǎng)上搜索了一下子 恍然大悟

具體如下 我是復(fù)制過來(lái)了 大家重點(diǎn)理解一下子它的實(shí)現(xiàn)思路 :


問題:

A域名下的頁(yè)面a.htm中通過iframe嵌入B域名下的頁(yè)面b.html,由于b.html的大小等是不可預(yù)知而且會(huì)變化的,所以需要 a.htm中的iframe自適應(yīng)大小.

問題本質(zhì) :

js的跨域問題,因?yàn)橐刂芶.htm中iframe的大小就必須首先讀取得到b.html的大小,A、B不屬于同一個(gè)域,js的訪問受限,讀取不 到b.html的大小.

解決方案:

首先前提是A,B是合作關(guān)系,b.html中能引入A提供的js

首先a.html中通過iframe引入了b.html

復(fù)制代碼 代碼如下:
<iframe id="aIframe" height="0" width="0" src="http://www.b.com/html/b.html" frameborder="no" border="0px" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="yes" ></iframe>
<iframe id="aIframe" height="0" width="0" src="http://www.b.com/html/b.html" frameborder="no" border="0px" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="yes" ></iframe>

B在b.html中引入了A提供的js文件

Html代碼
復(fù)制代碼 代碼如下:
<script language="Javascript" type="text/Javascript" src="http://www.a.com/js/a.js"></script>

該js首先讀取b.html的寬和高,然后創(chuàng)建一個(gè)iframe,src為和A同一個(gè)域的中間代理頁(yè)面a_proxy.html,吧讀取到的寬和 高設(shè)置到src的hash里面

Html代碼
復(fù)制代碼 代碼如下:
<iframe id="iframeProxy" height="0" width="0" src="http://www.a.com/html/a_proxy.html#width|height" style="display:none" ></iframe>

a_proxy.html是A域下提供好的中間代理頁(yè)面,它負(fù)責(zé)讀取location.hash里面的width和height的值,然后設(shè)置與 它同域下的a.html中的iframe的寬和高.

Js代碼
復(fù)制代碼 代碼如下:
var pParentFrame = parent.parent.document.getElementById("aIframe");
var locationUrlHash = parent.parent.frames["aIframe"].frames["iframeProxy"].location.hash;
pParentFrame.style.width = locationUrlHash.split("#")[1].split("|")[0]+"px";
pParentFrame.style.height = locationUrlHash.split("#")[1].split("|")[1]+"px";
var pParentFrame = parent.parent.document.getElementById("aIframe");
var locationUrlHash = parent.parent.frames["aIframe"].frames["iframeProxy"].location.hash;
pParentFrame.style.width = locationUrlHash.split("#")[1].split("|")[0]+"px";
pParentFrame.style.height = locationUrlHash.split("#")[1].split("|")[1]+"px";

這樣的話a.html中的iframe就自適應(yīng)為b.html的寬和高了.

其他一些類似js跨域操作問題也可以按這個(gè)思路去解決

JavaScript技術(shù)js跨域問題之跨域iframe自適應(yīng)大小實(shí)現(xiàn)代碼,轉(zhuǎn)載需保留來(lái)源!

鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。

主站蜘蛛池模板: 上杭县| 南京市| 阳春市| 开平市| 乌拉特后旗| 轮台县| 年辖:市辖区| 梁山县| 涞源县| 白沙| 长顺县| 平罗县| 梅州市| 安化县| 潞城市| 虞城县| 华坪县| 苗栗县| 将乐县| 项城市| 田阳县| 浦江县| 岳阳市| 大余县| 信阳市| 精河县| 沙坪坝区| 台东县| 谷城县| 志丹县| 宣恩县| 山阴县| 蒙自县| 邯郸市| 石首市| 洛南县| 双柏县| 宁晋县| 介休市| 财经| 牙克石市|