javascript - 防止 Element.scrollIntoView() 函数(其中 Element 在 iframe 中)滚动父级
问题描述
我有一个具有以下功能的页面:
function aux_func(_this){
let link = document.getElementById("oLink").href;
var elmnt = _this.contentDocument.getElementById(link);
elmnt.scrollIntoView({ behavior: "smooth", block: "center" });
}
其中 oLink 是页面中的一个元素,elmnt 是在 iframe 的 srcdoc 中加载的 html 中的链接。
该函数是这样调用的:
<iframe id="cFrame" srcdoc="{{t1}}" onload="aux_func(this)"></iframe>
其中 {{t1}} 是 Django 发送的一些 html(我正在使用模板)。并且 iframe 在页面中(从现在起我将其称为父级)。
无论如何,我想在加载框架内容时自动滚动到 elmnt。但我想防止父级被滚动。所以我只希望 iframe 的滚动条移动。
知道怎么做吗?我不能使用:
overflow: hidden
或任何类似的属性,因为我仍然需要访问父级和 iframe 中的其他元素。
解决方案
我知道它只是破解,但是在向下滚动 iframe 之后,向上滚动窗口怎么样。在函数末尾添加:
window.scrollTo(0, 0);
这应该让 iframe 滚动,但页面会跳回顶部。如果在页面加载时加载 iframe,则效果很好。或者,您可以保存页面当前所在的位置,然后在滚动 iframe 后滚动回该位置。
推荐阅读
- sql - 如何有效地过滤 SQL 结果
- c - 计数无法正确打印
- javascript - JSON 到 Javascript 类
- powershell-3.0 - 用于添加辅助 IP 地址的 PowerShell 3.0 脚本
- vb.net - “光标”类型的值不能转换为“短”
- spring-boot - 在生产部署(jar/war)中使用 spring boot 时有什么推荐
- r - 在 zoo 包中限制 na.locf
- sql - 通过具有三个外键的其他表 Postgresql 选择值
- firebase - 在 Dialogflow 项目中使用 Firestore 数据库
- r - 用于以下任务的矢量化方法