You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现鼠标悬停右侧列时滚动到底部后触发中间列滚动

实现侧边栏滚动到底部后联动中间列滚动

我有一个三列布局的网页,左右列宽度固定,中间列占据剩余可用宽度,所有列均设置overflow: auto以支持垂直滚动。希望实现:当鼠标位于右侧列内,滚动至该列底部后,中间列开始滚动(同理,滚动到顶部后继续向上滚动,中间列也会滚动)。原因是右侧列通常没有足够内容需要垂直滚动,此时若鼠标恰好悬停在右侧列上并尝试用滚轮滚动,网页会显得“失效”。X(Twitter)网页版的效果正是我想要的,请问如何实现,是否需要JavaScript?


现有代码示例

HTML

<div class="container">
  <div class="col" id="a"></div>
  <div class="col" id="b"></div>
  <div class="col" id="c"></div>
</div>

CSS

.container {
  display: flex;
  position: fixed;
  inset: 0;
  background-color: green;
  width: 100%;
}
.col {
  position: relative;
  height: 100%;
  overflow: auto;
}
#a {
  width: 200px;
  background-color: blue;
}
#b {
  width: 100%;
  background-color: lightgrey;
}
#c {
  width: 200px;
  background-color: red;
}

JS(填充测试内容)

function addText(id) {
  let elem = document.getElementById(id);
  for(let i=0; i<50; i++){
    let child = document.createElement('div');
    child.innerText = `${i%10}`.repeat(200);
    elem.appendChild(child);
  }
}
['a','b','c'].forEach(addText);

实现方案

必须使用JavaScript,因为CSS无法实现这种跨元素的滚动联动逻辑。核心思路是监听侧边栏的滚轮事件,判断其是否已经滚动到边界,若已到达边界则将滚轮事件的滚动行为转移到中间列。

修改后的JavaScript代码

function addText(id) {
  let elem = document.getElementById(id);
  for(let i=0; i<50; i++){
    let child = document.createElement('div');
    child.innerText = `${i%10}`.repeat(200);
    elem.appendChild(child);
  }
}
['a','b','c'].forEach(addText);

// 获取目标元素
const rightCol = document.getElementById('c');
const mainCol = document.getElementById('b');

// 监听右侧列的滚轮事件
rightCol.addEventListener('wheel', (e) => {
  const isScrollingDown = e.deltaY > 0;
  const isAtBottom = rightCol.scrollTop + rightCol.clientHeight >= rightCol.scrollHeight;
  const isAtTop = rightCol.scrollTop <= 0;

  // 向下滚动且已到底部,或者向上滚动且已到顶部时,转移滚动行为到中间列
  if ((isScrollingDown && isAtBottom) || (!isScrollingDown && isAtTop)) {
    e.preventDefault(); // 阻止右侧列的默认滚动
    // 让中间列滚动,deltaY的数值控制滚动幅度
    mainCol.scrollTop += e.deltaY;
  }
});

逻辑说明

  • 监听右侧列的wheel事件,通过deltaY的正负判断滚动方向
  • 判断右侧列是否处于滚动边界:
    • 向下滚动时:scrollTop + clientHeight >= scrollHeight表示已滚动到底部
    • 向上滚动时:scrollTop <= 0表示已滚动到顶部
  • 当到达边界时,阻止右侧列的默认滚动行为,手动修改中间列的scrollTop值,实现滚动联动

内容的提问来源于stack exchange,提问作者Andrew Parks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:07:39