在iFrame中使用Window.find()时如何禁用自动滚动 [英] How to disable auto-scrolling when using Window.find() inside an iFrame

查看:57
本文介绍了在iFrame中使用Window.find()时如何禁用自动滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a search function that finds keywords inside an iFrame that looks like this:

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" 不会具有相同的滚动锁定效果.

The issue occurs when iWindow.find(keyword) is executed, for every match found the page will automatically scroll to it's location on the page. This at times causes a scroll to the very bottom of the page if a match happens to be there. I am using this same logic for elements not inside an iFrame and everything works smoothly with no scrolling as long as I include document.designMode = "on". For some reason setting iframe.contentDocument.designMode = "on" does not have the same scroll-lock effect.

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

Any suggestions on how to disable scrolling while the iWindow.find() is being performed?

推荐答案

您可以在整个while循环完成之前禁用滚动,然后在其之后重新启用滚动.像这样:

You can disable scroll just before and re-enable it just after the whole while loop is done. Something like this:

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

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

Where noScroll is your function that disables scrolling (something like window.scrollTo(0,0)). I've found useful adding the setTimeout in a script I was working on, otherwise the last event won'f fire. It may be useless in your case.

这篇关于在iFrame中使用Window.find()时如何禁用自动滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆