简体   繁体   中英

prevent iframe from scrolling parent document when calling focus

I have an iframe that calls someElement.focus . When this happens the parent scrolls to show the iframe. How can I prevent the parent from scrolling? Effectively I want the iframe itself to scroll so within the iframe the correct element is scrolled into space of the iframe itself but the parent page should be unaffected.

 const lines = new Array(100).fill(0).map((e,i) => i).join('\\n') const script = 'script'; const frameContent = ` <style> pre { font-size: 60pt; } </style> <body> <pre>${lines}</pre> <input type="text" id="target"> </body> <${script}> document.querySelector('#target').focus(); </${script}> `; document.querySelector('pre').textContent = lines; const iframe = document.querySelector('iframe'); iframe.src = URL.createObjectURL(new Blob([frameContent], {type: 'text/html'}));
 <style> pre { font-size: 60pt; } } </style> <div>you should see this element</div> <pre></pre> <iframe></iframe> <div>you should NOT be scrolled to see this element</div>

It makes sense to me that calling focus would move the input area on to the screen, but at the same time, it makes no sense to me that any random iframe can get the parent page to jump to it on demand by calling focus.

Is it possible to prevent the iframe from affecting the parent?

You can try passing options when setting focus:

document.querySelector('#target').focus({preventScroll: true});

The preventScroll option is described in the MDN docs on HTMLElement.focus() .

Note that this will likely only work for same-origin iframes.

Browsers apply restrictions that might prevent the preventScroll option being respected inside cross-origin/third-party iframes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM