簡體   English   中英

在 Javascript 中的 iFrame 中觸發滾動事件的問題

[英]Problem triggering a scroll event in an iFrame in Javascript

我在這方面遇到了困難,盡管互聯網上的很多人似乎都有同樣的問題,但網上沒有任何解決方案對我有用。

我有以下 html 代碼:

<iframe id="documentIFrame" src='http://localhost:49551//Documents/System/ef4be80c-a8d8-482e-9792-50c5692aa07f.pdf' width='100%' height='100%' frameborder='0'></iframe>

然后這是我嘗試過的以下js代碼:

1)

$("#documentIFrame").on('load', function () {
                var iframe = document.getElementById('documentIFrame');
                iframe.contentDocument.addEventListener('scroll', function (event) {
                    console.log("SCROLL");
                }, false);
            });

這顯示沒有結果,它甚至不會進入function。

2.

            var iframe = $("#documentIFrame").contentWindow;
            
            $(iframe).scroll(function () {
                console.log("NOW SCROLLING...");
                if ($(iframe).scrollTop() == $(iframe).height() - $("#documentIFrame").height()) {
                    alert("Reached bottom!");
                }
            });

和以前一樣,完全沒有結果。

3)

                var iframe = document.getElementById("documentIFrame").contentWindow;
                console.log(iframe);


                iframe.onscroll = function () {
                    console.log("scrolling...");
                }

一樣,沒有結果。

EDIT: Some extra info on this one, in this case, if I console.log() the iframe AFTER I assign the function to the onscroll event, and I search within the iframe , the onscroll event appears as null .

編輯2:這對你們中的一些人來說可能會派上用場,使用jQuery到 select .contentWindow對我不起作用,它是undefined ,但如果我使用普通的 JS 代碼:

document.getElementById("documentIFrame").contentWindow;

...然后它返回元素就好了。

我也嘗試過.contents()contentDocument而不是contentWindow ,結果是一樣的; 如果我嘗試console.log()這些元素,它們總是未定義。

我嘗試在document.ready()和 function 上設置滾動 function 我調用由不同組件觸發的 onclick 事件; 總是相同的結果。

我讀過一些關於同源政策的文章,但我認為不應該是這樣,因為這個文件(在iframesrc中的那個)來自本地主機,應該作為“同源”傳遞,對嗎?

任何幫助將不勝感激。

這似乎對我有用:

document
  .querySelector('#documentIFrame')
  .addEventListener('load', e => {
    e.target.contentWindow.addEventListener('scroll', e => {
      console.log('scrollin');
    });
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM