需求场景:
- 父页面A 包含有iframe页面B,
- 页面B内容很长,浏览器一两屏不能显示全,需要滚动显示。
- 当浏览器滚动的时候,iframe B页面中的某一内容不能需要固定在窗口的某一位置。如下图中的 回到顶部按钮。
解决思路:
- iframe子页面初始化时重新定义top窗口的onscroll事件函数
- onscroll事件函数中获取相关父页面的clientHeight等参数,根据clientHeight及scrollTop的值重新设置 需要固定显示的div的top、left值。
简单实现:
iframe 页面内的相关代码如下:
setWindowScrollTop 中高度加100是父页面与iframe B页面顶部的间距
<div id="id_return_top" style="position:absolute;top: 158px; left: 245px;"> <a href="javascript:setScrollTop(0);" class="return_btn"></a> </div> <script type="text/javascript"> top.window.onscroll = function() { var windowHeight = getWindowHeight(self)-150;
var lvTop=parseInt(getWindowHeight(top))+parseInt(getWindowScrollTop(top))-250; lvTop = lvTop<=0?1:lvTop; lvTop = lvTop>windowHeight?windowHeight:lvTop;
document.getElementById("id_return_top").style.top=lvTop+"px"; document.getElementById("id_return_top").style.left="245px"; } </script> |
获取window 的height及scrollTop的相关js代码:
function getWindowScrollTop(win){
var scrollTop=0;
if(win.document.documentElement&&win.document.documentElement.scrollTop){
scrollTop=win.document.documentElement.scrollTop;
}else if(win.document.body){
scrollTop=win.document.body.scrollTop;
}
return scrollTop;
}
function getWindowHeight(win){
var clientHeight=0;
if(win.document.body.clientHeight&&win.document.documentElement.clientHeight){
clientHeight = (win.document.body.clientHeight<win.document.documentElement.clientHeight)?win.document.body.clientHeight:win.document.documentElement.clientHeight;
}else{
clientHeight = (win.document.body.clientHeight>win.document.documentElement.clientHeight)?win.document.body.clientHeight:win.document.documentElement.clientHeight;
}
return clientHeight;
}