簡體   English   中英

使用父窗口滾動iframe

[英]scrolling iframe with parent window

如何同時滾動父窗口和滾動iframe。我的意思是說,如果有人滾動iframe,它也應該滾動父窗口。 我正在考慮通過javascript實現此目的。 起源是相同的。

由於兩個文檔共享相同的原點,因此您不受相同的原點策略的限制,這意味着您可以從一個文檔中的javascript調用另一文檔中的javascript。

一個簡單的例子:

index.html

<html>
    <head>
        <script>
            function handleMessage(msg) {
                console.log("message from iframe: ", msg);
            }

            function sendMessage() {
                let msg = {
                    value: document.getElementById("message").value
                }

                document.getElementById("iframe").contentWindow.handleMessage(msg);
            }
        </script>
    </head>
    <body>
        <input type="text" id="message" />
        <button onclick="sendMessage()">send message to parent</button>
        <br/><br/>
        <iframe id="iframe" src="iframe.html"></iframe>
    </body>
</html>

iframe.html

<html>
    <head>
        <script>
            function handleMessage(msg) {
                console.log("message from parent: ", msg);
            }

            function sendMessage() {
                let msg = {
                    value: document.getElementById("message").value
                }

                parent.handleMessage(msg);
            }
        </script>
    </head>
    <body>
        <input type="text" id="message" />
        <button onclick="sendMessage()">send message to parent</button>
    </body>
</html>

既然您知道如何從一個文檔調用js方法到另一個文檔,那么它應該足夠簡單,以捕獲一個文檔中的滾動事件,然后讓另一個文檔知道滾動增量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM