国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > HTML > 正文

iframe自適應大小

2024-08-26 00:09:36
字體:
來源:轉載
供稿:網友

頁面域關系

主頁面a.html所屬域a:www.taobao.com
被iframe的頁面b.html所屬域b:www.alimama.com,假設地址:http://www.alimama.com/b.html

實現效果

a域名下的頁面a.html中通過iframe嵌入b域名下的頁面b.html,由于b.html的寬度和高度是不可預知而且會變化的,所以需要a.html中的iframe自適應大小.

問題本質:

js對跨域iframe訪問問題,因為要控制a.html中iframe的高度和寬度就必須首先讀取得到b.html的大小,a、b不屬于同一個域,瀏覽器為了安全性考慮,使js跨域訪問受限,讀取不到b.html的高度和寬度.

解決方案:

引入代理代理頁面c.html與a.html所屬相同域a,c.html是a域下提供好的中間代理頁面,假設c.html的地址:www.taobao.com/c.html,它負責讀取location.hash里面的width和height的值,然后設置與它同域下的a.html中的iframe的寬度和高度.

代碼如下:

a.html代碼

首先a.html中通過iframe引入了b.html
<iframe id=”b_iframe” height=”0′ width=”0′ src=”http://www.alimama.com/b.html” frameborder=”no” border=”0px” marginwidth=”0′ marginheight=”0′ scrolling=”no” allowtransparency=”yes” ></iframe>

b.html代碼

<script type=”text/javascript”>
  var b_width = math.max(document.documentelement.clientwidth,document.body.clientwidth);
  var b_height = math.max(document.documentelement.clientheight,document.body.clientheight);
  var c_iframe = document.getelementbyid(”c_iframe”);
  c_iframe.src = c_iframe.src+”#”+b_width+”|”+b_height; //http://www.taobao.com/c.html#width|height”
}
</script>
<!–js讀取b.html的寬和高,把讀取到的寬和高設置到和a.html在同一個域的中間代理頁面車c.html的src的hash里面–>
<iframe id=”c_iframe”  height=”0′ width=”0′  src=”http://www.taobao.com/c.html” style=”display:none” ></iframe>

c.html代碼

<script type=”text/javascript”>
var b_iframe = parent.parent.document.getelementbyid(”b_iframe”);
var hash_url = window.location.hash;
var hash_width = hash_url.split(”#”)[1].split(”|”)[0]+”px”;
var hash_height = hash_url.split(”#”)[1].split(”|”)[1]+”px”;
b_iframe.style.width = hash_width;
b_iframe.style.height = hash_height;
</script>
a.html中的iframe就可以自適應為b.html的寬和高了.

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 石景山区| 四平市| 双江| 平和县| 双鸭山市| 沂源县| 涞源县| 全南县| 邵东县| 大方县| 汤阴县| 八宿县| 普宁市| 惠州市| 西充县| 龙泉市| 富阳市| 达孜县| 新安县| 文成县| 甘孜县| 宣武区| 云浮市| 富宁县| 专栏| 丹江口市| 突泉县| 漯河市| 吉首市| 泸州市| 汉寿县| 黑山县| 辉南县| 疏勒县| 荥阳市| 武威市| 阳原县| 五大连池市| 澄城县| 凤翔县| 修水县|