需求場景:
- 父頁面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;
}