参考文章 原生JS控制多个滚动条同步跟随滚动
<!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>
<style>
.div1,
.div2 {
width: 200px;
height: 300px;
float: left;
overflow: auto;
}
.div2 {
margin-left: 100px;
}
.div3 {
height: 800px;
background-color: red;
}
.div4 {
height: 800px;
background-color: blue;
}
</style>
</head>
<body>
<div class="div1">
<div class="div3"></div>
</div>
<div class="div2">
<div class="div4"></div>
</div>
</body>
<script>
let a = document.querySelector('.div1');
let b = document.querySelector('.div2');
let overElement = '';
a.onmouseover = () => {
overElement = 'a';
}
b.onmouseover = () => {
overElement = 'b';
}
a.addEventListener('scroll', () => {
if (overElement === 'a') {
b.scrollTop = a.scrollTop;
}
});
b.addEventListener('scroll', () => {
if (overElement === 'b') {
a.scrollTop = b.scrollTop;
}
});
</script>
</html>