首页 > 解决方案 > 在 iFrame 中使用 Window.find() 时如何禁用自动滚动

问题描述

我有一个搜索功能,可以在 iFrame 中查找关键字,如下所示:

const iWindow = iframe.contentWindow; 
iframe.contentDocument.designMode = "on"; //This is supposed to prevent scrolling but doesn't
while (iWindow.find(keyword)) {
    // Logic for found keyword handling here
}
iframe.contentDocument.designMode = "off";

执行时会出现问题iWindow.find(keyword),对于找到的每个匹配项,页面将自动滚动到页面上的位置。如果恰好有匹配项,这有时会导致滚动到页面的最底部。我对不在 iFrame 内的元素使用相同的逻辑,只要我包含document.designMode = "on". 由于某种原因设置iframe.contentDocument.designMode = "on"没有相同的滚动锁定效果。

关于如何在iWindow.find()执行时禁用滚动的任何建议?

标签: javascriptiframescroll

解决方案


您可以在整个 while 循环完成后禁用滚动并重新启用它。像这样的东西:

window.addEventListener('scroll', noScroll);
// find logic
setTimeout(() => window.removeEventListener('scroll', noScroll), 500);

禁用滚动的功能在哪里noScroll(类似于window.scrollTo(0,0))。我发现setTimeout在我正在处理的脚本中添加很有用,否则最后一个事件不会触发。在你的情况下它可能没用。


推荐阅读