DIV CSS 佈局教程網

用 JS 判斷 iframe 內網頁是否捲到底部並觸發事件
編輯:JavaScript綜合知識     

本文分享如何判斷 iframe 內的網頁是否捲動到底部,並在到底時觸發事件。

需求背景

曾有個需求是判斷 iframe 內的頁面是否捲到底。網上找來的資料多半是講當前頁面本身的情況,於是我自己研究了一下,找到可行的方法。

幾個關鍵屬性

先釐清三個屬性的含義:

1. clientHeight:元素可視區域的高度(佔用的顯示空間)。

2. scrollHeight:元素內容的實際總高度。

3. scrollTop:目前已捲動的距離。

程式碼

<iframe src="~/Files/3.html" id="iframepage" width="825"
        onload="func()"></iframe>
<script type="text/javascript">
function func() {
  var ifm = document.getElementById("iframepage");
  ifm.height = window.document.body.clientHeight - 100;
}
// 監聽 iframe 內部的捲動事件
window.document.getElementById("iframepage")
  .contentWindow.onscroll = function aaa() {
    var ifm = document.getElementById("iframepage")
      .contentWindow.document.documentElement;
    if (ifm.scrollTop == ifm.scrollHeight - ifm.clientHeight) {
      alert("到底了");
    }
  };
</script>

原理與相容性提醒

判斷的核心是這個等式:scrollTop == scrollHeight - clientHeight。當已捲動的距離等於「內容總高度減去可視高度」時,就代表捲到了最底部。透過 contentWindow 取得 iframe 內部的 document 物件,再監聽其 onscroll 事件即可。需要注意的是,這種跨文件存取要求父子頁面同來源;此外在 Chrome 中可能出現相容問題(網上有說法是需要架在伺服器環境下),而 Firefox 與 IE10 則無此問題。實作時務必在多個瀏覽器上實測驗證。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved