问题
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