How to disable auto-scrolling when using Window.find() inside an iFrame

[亡魂溺海] 提交于 2021-01-29 05:13:07

问题


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";

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.

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


回答1:


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);

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.



来源:https://stackoverflow.com/questions/64288173/how-to-disable-auto-scrolling-when-using-window-find-inside-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!