在父 html 中 获取 iframe 滚动条高度

652 阅读1分钟

父级 html 文件

原理:每个 iframe 有自己独立维护全局的 window 对象,相当于 父级里面 还包含了 一个 单独的 DOCTYPE html 文件;在父级获取子集的 body 或 documentElement 滚动条距离

 <div class="iframe-box" >
        <iframe id="my-frame" src="shear.html" frameborder="0"  style="border:0px; width: 100%" onLoad="setIframeHeight(this.id)"></iframe>
 </div>
 let doc = null
 function setIframeHeight(id) {
    var ifrm = document.getElementById(id);// iframe 标签
    doc = ifrm.contentDocument ? ifrm.contentDocument : ifrm.contentWindow.document;//#document 
}
let sa = setInterval(()=>{
    console.log(doc.documentElement.scrollTop);//iframe 滚动条高度
},200)