【问题标题】:How to disable auto-scrolling when using Window.find() inside an iFrame在 iFrame 中使用 Window.find() 时如何禁用自动滚动
【发布时间】:2020-10-13 16:24:23
【问题描述】:

我有一个搜索功能,可以在 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() 时禁用滚动有什么建议吗?

【问题讨论】:

  • 您在哪个浏览器上测试? Window.find 不在任何规范中,浏览器的行为可能会有所不同。
  • 目前在 Chrome 上测试,但 window.find 在 Firefox、Edge 和 IE 上也同样有效
  • 在尝试使用 iWindow.find(keyword) 时,我不断收到“未捕获的 DOMException:访问跨域对象上的属性“find”的权限被拒绝”。你不也得到这个错误吗?注意:我注释掉了设计模式行,因为 iframe.contentDocument 在 FF 中为空
  • @chadb768 你解决了这个问题?

标签: javascript iframe scroll


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-10-21
    • 1970-01-01
    • 2012-10-16
    • 2011-02-12
    • 2013-03-07
    • 2020-10-23
    • 2014-01-13
    • 2015-03-10
    • 1970-01-01
    相关资源
    最近更新 更多