iframe內部內容在瀏覽窗口位置固定的問題


需求場景:

  1. 父頁面A 包含有iframe頁面B,
  2. 頁面B內容很長,瀏覽器一兩屏不能顯示全,需要滾動顯示。
  3. 當瀏覽器滾動的時候,iframe B頁面中的某一內容不能需要固定在窗口的某一位置。如下圖中的 回到頂部按鈕。

 

 

解決思路:

  1. iframe子頁面初始化時重新定義top窗口的onscroll事件函數
  2. 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;

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM