javascript iframe跨域自适应高度

原理:通过在父窗口注册监听事件,子窗口获取事件并操作事件

方式方法:(插件方式 )
举例:比如,在yahoo页面需要放入一个iframe插件

1.制作一段js代码,大致如下:
  <script type="text/javascript" src="yahoo/v1/plugins-all.js">   </script>
  <script type="text/javascript">
CHAJIAN.Button.setup({href: "http://store.shopping.yahoo.co.jp/vitafelice/9034.html"});
</script>
  这是直接提供给yahoo的js插件,plugins-all.js内容如下:
 
  /**
* 提供给第三方代码
*/
var CHAJIAN = CHAJIAN || {};
(function(CHAJIAN ) {
var getHref = function() {
return window.location.href;
};
var getButton = function(setting) {
var _src = "http://192.168.0.108:7788/Plugins/voice.php?";
var _href = setting.href;
_href = typeof(_href) != "undefined"?_href:getHref();
_src =_src +"href="+_href;
var props = {};
props.width = "320";//default
props.id = "sp_iframe";
props.name = "sp_iframe";
props.frameborder = "0";
props.allowtransparency = "true";
props.marginhight = "0";
props.marginwidth = "0";
props.scrolling = "no";
props.src = _src;
SHOPAL.Utils.createElement("iframe",props,$("shopal"));
};
var $ = function(_objId) {
return document.getElementById(_objId);
};
// Button
CHAJIAN.Button = {};
CHAJIAN.Button.setup = function(setting) {
if (typeof (getButton) != "undefined") {
getButton(setting);
if (window.addEventListener) { //for W3C DOM
    window.addEventListener("message", receiveSize, false);
} else if (window.attachEvent) { //for IE
window.attachEvent("onmessage",receiveSize);
}
}
};
function receiveSize(e) {
        document.getElementById("sp_iframe").height = e.data;
    }

})(CHAJIAN);

************************以上是提供给第三方的代码,setting 可以是json格式的参数

2.在自己的域名下就可以这样设置父类(yahoo域名下)的iframe高度:

  /**
* timer autoSetHeight
* iframe跨域自适应高
*/
var sp_iframe_height = 0;
function autoSetHeight(){
var height = document.body.offsetHeight || document.body.scrollHeight; //offsetHeight/scrollHeight
var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);
if (typeof target != "undefined"){
    if (height != sp_iframe_height) {
    target.postMessage(height, '*');
    sp_iframe_height = height;
}
    }
};
setInterval(autoSetHeight,200);


大功告成。。。




http://blog.sina.com.cn/s/blog_61b570ab0100rhep.html
 

你可能感兴趣的:(JavaScript,iframe跨域自适应高度)