简体   繁体   中英

Prevent Element.scrollIntoView() function, where Element is in an iframe, from scrolling the parent

I have a page with the following function:

function aux_func(_this){
            let link = document.getElementById("oLink").href;
            var elmnt = _this.contentDocument.getElementById(link);
            elmnt.scrollIntoView({ behavior: "smooth", block: "center"  });
        }

Where oLink is an element in the page and elmnt is a link in the html loaded in the srcdoc of an iframe.

The function is called like this:

<iframe id="cFrame" srcdoc="{{t1}}" onload="aux_func(this)"></iframe>

Where {{t1}} is some html sent by Django (I am using templates). And the iframe is in the page (Ill call it parent from now on).

Anyways, I want to automatically scroll to elmnt when the frame content is loaded. BUT I want to prevent the parent from being scrolled. So I only want the iframe's scroll bars to move.

Any idea how to do that? I cannot use :

overflow: hidden

or any similar property as I still need to access other elements in the parent and the iframe.

I know its just hack, but how about after scrolling the iframe down, scroll the window back up. Adding this at the end of your function:

window.scrollTo(0, 0);

This should leave the iframe scrolled but the page would jump back to top. Works well if iframe is loaded when page is. Alternatively you could save the position the page is currently on, and then scroll back to that position after scrolling the iframe.

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