首页 > 解决方案 > 在 Javascript 中的 iFrame 中触发滚动事件的问题

问题描述

我在这方面遇到了困难,尽管互联网上的很多人似乎都有同样的问题,但网上没有任何解决方案对我有用。

我有以下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);
            });

这显示没有结果,它甚至不会进入函数。

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...");
                }

一样,没有结果。

编辑:关于这个的一些额外信息,在这种情况下,如果我console.log()iframe将功能分配给onscroll事件之后,我在 中搜索iframe,则onscroll事件显示为null.

编辑 2:这对你们中的一些人来说可能会派上用场,jQuery用于选择.contentWindow对我不起作用,它是undefined,但如果我使用纯 JS 代码:

document.getElementById("documentIFrame").contentWindow;

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

我也试过.contents()andcontentDocument而不是contentWindow,结果是一样的;如果我尝试使用console.log()这些元素,它们总是未定义。

我已经尝试在document.ready()另一个组件触发的 onclick 事件上调用的函数上设置滚动功能;总是相同的结果。

我读过一些关于同源政策的文章,但我认为不应该是这样,因为这个文件(在 中src的那个iframe)来自本地主机,应该作为“同源”传递,对吗?

任何帮助将不胜感激。

标签: javascripthtmljqueryiframedom-events

解决方案


这似乎对我有用:

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

推荐阅读