我在这个问题上遇到了困难,虽然互联网上的很多人似乎都有同样的问题,但网上没有任何解决方案对我有用。
我有以下 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()
和 contentDocument
而不是 contentWindow
,结果是一样的;如果我尝试 console.log()
那些元素,它们总是未定义的。我试过在
document.ready()
上设置滚动功能还有一个函数,我调用由不同组件触发的 onclick 事件;总是相同的结果。我读过一些关于同源策略的内容,但我认为不应该是这样,因为这个文档(
src
的 iframe
中的那个)来自本地主机,应该作为“同源“, 正确的?任何帮助将不胜感激。
最佳答案
这似乎对我有用:
document
.querySelector('#documentIFrame')
.addEventListener('load', e => {
e.target.contentWindow.addEventListener('scroll', e => {
console.log('scrollin');
});
});
关于javascript - 在 Javascript 中的 iFrame 中触发滚动事件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62566082/