Scenario:
- Parent page A contains iframe page B,
- Page B has a long content. The browser cannot display all the pages on one or two screens. You need to scroll the page.
- When the browser is rolling, a content in the iframe B page cannot be fixed at a certain position in the window. For example, return to the top button.
Solution:
- When initializing the iframe subpage, redefine the onscroll event function of the top window.
- The onscroll event function obtains clientHeight and other parameters of the parent page, and resets the top and left values of the div to be fixed based on the clientHeight and scrollTop values.
Simple implementation:
IframeThe Code on the page is as follows:
In setWindowScrollTop, the height plus 100 is the distance between the parent page and the top of the iframe B page.
<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 transport wheight = getmediawheight (self)-150; Var lvTop = parseInt (getWindowScrollTop (top) + parseInt (getWindowScrollTop (top)-250; LvTop = lvTop <= 0? 1: lvTop; LvTop = lvTop> running wheight? WindowHeight: lvTop; Document. getElementById ("id_return_top"). style. top = lvTop + "px "; Document. getElementById ("id_return_top"). style. left = "245px "; } </Script> |
Get windowHeightAnd scrollTopRelated jsCode:
Function getWindowScrollTop (win ){
Var scrollTop = 0;
If(win.document.documentelement&win.document.doc umentElement. scrollTop ){
ScrollTop=win.document.doc umentElement. scrollTop;
} Else if(win.doc ument. body ){
ScrollTop=win.doc ument. body. scrollTop;
}
Return scrolltop;
}
Function getwindowheight (WIN ){
VaR clientheight = 0;
If(win.document.body.clientheight&win.document.doc umentelement. clientheight ){
Clientheight = (win.doc ument. Body. clientheight <win.document.doc umentelement. clientheight )? Win.doc ument. Body. clientheight: win.document.doc umentelement. clientheight;
} Else {
ClientHeight = (win.doc ument. body. clientHeight> win.document.doc umentElement. clientHeight )? Win.doc ument. body. clientHeight: win.document.doc umentElement. clientHeight;
}
Return clientHeight;
}