javascript-如何检测 iframe 中的滚动事件? [英] javascript-How to detect scroll event in iframe?
问题描述
当我尝试使用 iframe 标签添加事件滚动时遇到问题.通常,我使用带有 div 标签的滚动事件它运行良好.但是当我在 iframe 标签中添加滚动事件来检测用户滚动 pdf 页面时,它不起作用.为什么我无法访问 iframe 中的 html 元素?,我有以下代码检查:
I have a problem when I try add event scroll with iframe tage. generally, I use scroll event with div tag It was working well. but when I add scroll event in iframe tag to detect user scroll pdf page, It was not working. why cannot I access html elements in iframe?, I have code inspect below:
我尝试使用 iframe 添加 javascript 滚动事件:
HTML 代码:
<iframe id="myframe" src="doc.pdf"></iframe>
JavaScript 代码:
document.getElementById('myframe').onscroll = function(){
alert('scrolling page');
};
推荐答案
一个iframe
没有scroll方法,iframe
的document
code> 确实 - 您需要引用内部 document
而不是 标签.
An iframe
does not have a scroll method, the document
of the iframe
does - you need to reference the inner document
rather than your <iframe>
tag.
您可以使用 iframe.contentDocument
引用它:
You can reference it with iframe.contentDocument
:
var iframe = document.getElementById('frame');
iframe.contentDocument.body.innerHTML = 'a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>';
iframe.contentDocument.addEventListener('scroll', function(event) {
console.log(event);
}, false);
<iframe id="frame"></iframe>
参见:https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement 了解更多信息
这篇关于javascript-如何检测 iframe 中的滚动事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!