javascript - 在 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
)来自本地主机,应该作为“同源”传递,对吗?
任何帮助将不胜感激。
解决方案
这似乎对我有用:
document
.querySelector('#documentIFrame')
.addEventListener('load', e => {
e.target.contentWindow.addEventListener('scroll', e => {
console.log('scrollin');
});
});
推荐阅读
- java - Spring Boot Kafka Consumer 未消费,Kafka Listener 未触发
- angular - 何时使用 createSpy、createSpyObject 和 spyOn?
- javascript - 屏幕上的 Javascript 触发器(进度条)
- transpiler - 为转译而构建的抽象(编程)语言
- android - 在 Android 中如何使用 Java 添加内部图像?
- vue.js - 如何在 VueJS 中使用计算属性映射嵌套的 Vuelidate 验证对象?
- go - 如何有效地计算文件的校验和
- c# - .net core 3.1 身份不断强制用户在短时间内使用身份登录
- javascript - 将非嵌套 JSON 数组解析为 HTML 树视图?
- c - 使用 C 读取 4 字节整数 (Int32) 文件失败