How to sync the scroll bar for 2 iframe

2020-08-07 11:29发布

问题:

I have a task to launch 2 web pages in a single html page and do the web page comparsion side by side, so I have create 2 iframes for each comparing web page, however I have a problem on sync the scroll bar behaviour, like when I move the vertical scroll bar on the left side web page(iframe1), then the scroll bar on right side web page(iframe2) will move as well. Is there anyone know how to do it? or other method beside using iframe, but available to launch 2 web pages and sync the scroll bar? Thanx.

回答1:

You can access the iframe's window using the contentWindow attribute.

Register a scroll handler, contentWindow.onscroll, and you can scroll using scrollTo.

Security note: the content of the iframe's should be from the same domain as the top-level page, before it can access contentWindow's values, because cross-domain Javascript access is blocked.

frame1.contentWindow.onscroll = function(e) {
   frame2.contentWindow.scrollTop = frame1.contentWindow.scrollTop;
   frame2.contentWindow.scrollLeft = frame1.contentWindow.scrollLeft;
};