首页 > 解决方案 > 防止 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 中的其他元素。

标签: javascriptjqueryhtmlcssiframe

解决方案


我知道它只是破解,但是在向下滚动 iframe 之后,向上滚动窗口怎么样。在函数末尾添加:

window.scrollTo(0, 0);

这应该让 iframe 滚动,但页面会跳回顶部。如果在页面加载时加载 iframe,则效果很好。或者,您可以保存页面当前所在的位置,然后在滚动 iframe 后滚动回该位置。


推荐阅读