js postMessage實現iframe同步滾動對比

在這裏插入圖片描述

注意:不能用絕對路徑打開html,否則報錯 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('null') does not match the recipient window's origin ('null').

1.index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <iframe src="./A.html" frameborder="0" id="myframeA"></iframe>
    <iframe src="./B.html" frameborder="0" id="myframeB"></iframe>
</body>
<script>
    window.addEventListener('message', function(data) {
        var { page, data } = data.data;
        if (page == 'a') {
            document.getElementById("myframeB").contentWindow.postMessage({
                data: data
            }, '*');
        } else if (page == 'b') {
            document.getElementById("myframeA").contentWindow.postMessage({
                data: data
            }, '*');
        }
    })
</script>

</html>
2.A.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <p>A1</p>
    <p>A2</p>
    <p>A3</p>
    <p>A4</p>
    <p>A5</p>
    <p>A6</p>
 	...
    <p>A98</p>
    <p>A99</p>
    <p>A100</p>
</body>
<script>
    var a = true //用於避免手動設置scrollTop 時觸發scroll事件,整個頁面抖動
    window.onscroll = function() {
        if (a) {
            window.parent.postMessage({ page: 'a', data: document.documentElement.scrollTop })
        } else {
            a = true
        }
    }
    window.addEventListener('message', function(data) {
        a = false
        document.documentElement.scrollTop = data.data.data
    })
</script>

</html>
3.B.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <p>B1</p>
    <p>B2</p>
    <p>B3</p>
    <p>B4</p>
    <p>B5</p>
    <p>B6</p>
 	...
    <p>B98</p>
    <p>B99</p>
    <p>B100</p>
</body>
<script>
    var b = true //用於避免手動設置scrollTop 時觸發scroll事件,整個頁面抖動
    window.onscroll = function() {
        if (b) {
            window.parent.postMessage({ page: 'b', data: document.documentElement.scrollTop })
        } else {
            b = true
        }
    }
    window.addEventListener('message', function(data) {
        b = false
        document.documentElement.scrollTop = data.data.data
    })
</script>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章