跨域、字页面高度动态变化
这里结合了第2、第4两种方法,我的想法是在B页面通过一个计时器,不停计算B页面的高度,一但变化,马上修改iframe标签的src属性,而C页面也有计时器不断监听src的变化,改变Aiframe标签的高度。需要注意的是仅仅修改src属性后面的锚点值(如“#1234”),页面并不会刷新,不会重新请求,这也是在C页面增加计时器的原因。
DEMO
//B页面脚本 (function(){ var getHeight = function(){ return Math.max(document.documentElement.scrollHeight,document.body.scrollHeight); }; var preHeight = getHeight(), agent_iframe; var createIframe = function(height){ agent_iframe = document.createElement("iframe"); agent_iframe.style.height = "0"; agent_iframe.style.width = "0"; agent_iframe.style.border = "none"; agent_iframe.src = "http://demo.zhouqicf.com/js/2010/iframe_height/agent_iframe.html#" + height; document.body.appendChild(agent_iframe); } createIframe(preHeight); var checkHeight = function(){ var currentHeight = getHeight(); if(currentHeight != preHeight){ agent_iframe.src = "http://demo.zhouqicf.com/js/2010/iframe_height/agent_iframe.html#" + currentHeight; preHeight = currentHeight; } setTimeout(checkHeight,500); } setTimeout(checkHeight,500); })();
//C页面脚本 (function(){ var preHeight = parseInt(window.location.hash.substring(1),10), ifrmae = window.top.document.getElementById("frame_content_parent"); ifrmae.height = preHeight; setInterval(function(){ var newHeight = parseInt(window.location.hash.substring(1),10); if (newHeight !== preHeight){ ifrmae.height = newHeight; preHeight = newHeight; } },500); })();
这里还有另一种方案,就是让iframe每一次都重新请求,这样C页面就不需要计时器了,但是如果2次计算高度重复的话,就会导致src属性的值相同,这样浏览器就很可能不重新请求该页面了,那么C页面中的脚本也就不运行了。要修复这个问题很简单,只要在每次计算出来的src属性上增加一个随机数的参数就行了。比如http://demo.zhouqicf.com/js/2010/iframe_height/agent_iframe.html?temp=123123423712937#1563
//B页面关键脚本 agent_iframe.src = "http://demo.zhouqicf.com/js/2010/iframe_height/agent_iframe.html?a=" + Math.random() + "#" + currentHeight;
//C页面脚本 window.top.document.getElementById("frame_content_parent").height = parseInt(window.location.hash.substring(1),10);
原文:http://ued.koubei.com/?p=1217
本文链接:http://www.blueidea.com/tech/web/2010/7986.asp
出处:口碑网UED Team
责任编辑:bluehearts
上一页 三谈Iframe自适应高度 [2] 下一页
◎进入论坛网页制作、WEB标准化版块参加讨论,我还想发表评论。
|