gpt4 book ai didi

javascript - 尝试获取 iframe 中元素的 .offset().top 值时未定义

转载 作者:行者123 更新时间:2023-12-03 04:51:04 26 4
gpt4 key购买 nike

我在使用 Firefox 和 Safari 时遇到了一个问题,当尝试从 iframe 中的元素获取 .offset().top 值时,我在尝试获取该值时得到了未定义的结果。这似乎在 Chrome、Edge 和 IE 中运行良好,但在 Firefox 或 Safari 中则不然。

这是网址:

https://twlatl.github.io/styleguide/

当您在 Firefox 中单击导航时,您会在控制台中看到错误。

类型错误:this.$iframeContent.find(...).offset(...)未定义

引起问题的 block 在这里:

gotoAnchor: function($elem) {
window.location.hash = '!' + $elem.attr('href').replace('#', '');
this.top = this.$iframeContent.find('h1' + $elem.attr('href')).offset().top;
this.$iframeContent.find('html, body').animate({
scrollTop: this.top
}, 800);
},

从元素中删除 .offset().top 可以消除错误,但也会删除滚动到页面该部分的功能。

我尝试将此变量包装在 .on() 方法中以检查 iframe 是否首先完全加载,但这不起作用。

最佳答案

尝试一下(您可以重组以满足您的需求)

var iframe = document.body.querySelector('.hgt-iframe-wrapper > iframe')
var iframeBody = iframe.contentDocument.body
var sectionHeader = iframeBody.querySelector($elem.attr('href'))

if( sectionHeader ){
sectionHeader.scrollIntoView()
}

Note: you'll get an error with this ^ because ID's aren't allowed to start with numbers. Change the section header ID's to start with a letter and it will work

更新

啊,你的问题是你在加载 iframe 之前访问它的内容。如果您有时刷新,它加载得足够快并且您的菜单可以工作。您可以在下面的屏幕截图中看到 iframe 加载速度不够快,因此 this.$iframeContent实际上是空的(没有返回 <div> )

enter image description here

关于javascript - 尝试获取 iframe 中元素的 .offset().top 值时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42656811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com