iframe 跨域高度自適應

問題描述:A頁面如今要使用iframe嵌套一個不一樣域的C頁面,A頁面iframe的高度取決於C頁面的高度,而C頁面的高度不是肯定的。因此A頁面中的iframe要根據C頁面的高度自動調整。javascript

解決方案:html

使用一個代理頁面B來聯通A和C這兩個不一樣域的頁面。java

實現方法:跨域

============================================================================app

A.html頁面jsp

www.shz.com:8080/cms/iframe/A.html(也能夠是jsp頁面)中嵌套C頁面代碼:測試

<iframe src="http://www.cms.com/C.html" id="iframe-content" name="ssymid" frameBorder=0 scrolling=no width="100%"></iframe>url

============================================================================spa

B.html操作系統

www.shz.com:8080/cms/iframe/B.html(也能夠是jsp頁面)代理頁面   注:代理頁面要和A頁面同域

頁面內容:

 

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>iframe代理頁面</title></head>
<body>
<script>
function  pseth() {
    var iObj = parent.parent.document.getElementById(iframe-content);
    iObjH = parent.parent.frames["iframe-content"].frames["iframeC"].location.hash;
    iObj.style.height = iObjH.split("#")[1]+"px";
}
pseth();
</script>
</body>
</html>

=======================================================================

C.html頁面

C.html(也能夠以jsp頁面)

在被嵌入的頁面中加上一個display:none的iframe,指向代理頁面

<iframe id="iframeC" name="iframeC" src="" width="0" height="0" style="display:none;" ></iframe>
<script type="text/javascript">
    function sethash(){
       var hashH = document.documentElement.scrollHeight; 
       var urlC = "http://www.shz.com:8080/cms/iframe/B.html";  //注:路徑必定要是域名,使用IP無效
        document.getElementById("iframeC").src=urlC+"#"+hashH;
    }
    window.onload=sethash;
</script>

 =======================================================================

總結:iframe跨域高度自適應的問題,網上都是能夠找到的,可是須要注意的就是被嵌入C頁面隱藏的iframe的指向地址必定要爲域名,不可使用ip,使用ip是無效的。

可是咱們通常都會在本身的電腦上測試,或者在測試機上測試。而本身的電腦和測試機通常都沒有域名,咱們常常適應Ip來訪問。咱們可使用計算機操做系統自帶的域名映射來實現,ip到域名的映射,具體方法以下:

一、找到系統的域名重定向文件:如C:\Windows\System32\drivers\etc 路徑下的hosts文件

二、打開文件

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
# 127.0.0.1       localhost
# ::1             localhost

三、在文件最後加上以下內容:

 10.124.8.208    www.cms.shz.com       

說明:前面是IP地址  後面是自定義的域名   二者要用空格隔開

經過以上三步,你就可使用自定義的域名將以前訪問地址中ip取代

相關文章
相關標籤/搜索