需求是: 有个在服务器上的html文件,希望在vue项目的页面里去预览该文件内容,并且监听查看内容完毕后(即内容滚到底部后)再进行一些操作
先附上已成功的代码
<iframe :src="cont" class="f-cont" ref="myIframe"></iframe>
window.addEventListener('message', (event) => {
if (event.data === 'scrollToBottom') {
console.log('已经滑动到底部');
}
}, false);
在html文件里增加代码
window.addEventListener('scroll', function() {
const isBottom = window.innerHeight + window.pageYOffset >= document.body.offsetHeight;
if (isBottom) {
parent.postMessage('scrollToBottom', '*');
}
});
这是分隔线 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
拿到该需求,就在思考,必须得拿到iframe里的DOM结构,所以,开始敲代码,如下
// iframe 加载完成后才能获取iframe 内部的 DOM 元素
handleIframeLoad() {
// 获取 iframe dom 对象
const iframe = this.$refs.myIframe;
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
// 监听 iframe 内容滚动事件
iframeDocument.addEventListener('scroll', this.handleIframeScroll);
},
// iframe 内容滚动事件回调
handleIframeScroll(e) {
const iframe = this.$refs.myIframe;
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
const isScrollToBottom = ((iframeDocument.documentElement.clientHeight + iframeDocument.documentElement.scrollTop) - iframeDocument.documentElement.scrollHeight) >= 0;
if (isScrollToBottom) {
console.log('已滚动到底')
}
},
发测试站,手机测试,🍎手机ok,安卓手机问题多多,所以,开始在网上百度兼容安卓手机的方法,找到
该方法: 在该示例代码中,我们使用 MutationObserver
监听 iframe 内容变化:通过 MutationObserver
可以监控 DOM 元素的变化,从而实现监听 iframe 内容滚动事件的效果。
<template>
<div>
<iframe ref="myIframe" src="./path/to/your/iframe.html"></iframe>
</div>
</template>
<script>
export default {
methods: {
handleIframeLoad() {
const iframe = this.$refs.myIframe;
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
const observer = new MutationObserver((mutations) => {
const iframeScroll = iframeDocument.scrollingElement || iframeDocument.body;
const htmlScroll = document.documentElement;
const iframeIsBottom = iframeScroll.scrollHeight - iframeScroll.scrollTop - iframeScroll.clientHeight <= 1;
const htmlIsBottom = htmlScroll.scrollHeight - htmlScroll.scrollTop - window.innerHeight <= 1;
if (iframeIsBottom || htmlIsBottom) {
console.log('已经滑动到底部');
}
});
observer.observe(iframeDocument.documentElement, { attributes: true, childList: true, subtree: true });
}
},
mounted() {
const iframe = this.$refs.myIframe;
iframe.addEventListener('load', this.handleIframeLoad);
}
}
</script>