js 双窗口同步滚动

JS | 双窗口同步滚动 | 简易 | demo | vue | tailwindcss

Posted by luoruiqing on July 15, 2022

实现效果

img

核心代码

1
2
3
function scrollSync(syncTarget, sourceTarget) {
    syncTarget.scrollTop = sourceTarget.scrollTop / (sourceTarget.scrollHeight - sourceTarget.clientHeight) * (syncTarget.scrollHeight - syncTarget.clientHeight)
}

主要是利用目标滚动条长度进行百分比折算,重置 scrollTop 树形来控制滚动条高度

参数解释

  • syncTarget: 同步目标DOM
  • sourceTarget: 来源目标DOM

这里主要是提供思路,如果场景不同,可以修改上面的计算公式;弱是性能消耗过高,可以增加节流函数处理。

Dome(Vue)

这里使用了tailwindcss布局样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>双窗口同步滚动</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="h-screen p-4">
    <div id="app">
        <section class="flex w-80 h-80 space-x-4">
            <ul ref="a" @scroll="scrollSync($refs.b, $event.target)" class="flex-1 overflow-y-auto space-y-1">
                <li v-for="i in 10" :key="i" class="h-20 flex justify-center items-center bg-gray-300 border border-red-400">red - </li>
            </ul>
            <ul ref="b" @scroll="scrollSync($refs.a, $event.target)" class="flex-1 overflow-y-auto space-y-1">
                <li v-for="i in 10" :key="i" class="h-20 flex justify-center items-center bg-gray-300 border border-blue-400">blue - </li>
            </ul>
        </section>
    </div>
</body>
<script>
    function scrollSync(syncTarget, sourceTarget) {
        syncTarget.scrollTop = sourceTarget.scrollTop / (sourceTarget.scrollHeight - sourceTarget.clientHeight) * (syncTarget.scrollHeight - syncTarget.clientHeight)
    }
    var app = new Vue({
        el: '#app',
        methods: { scrollSync },
    })
</script>

</html>