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

鼠标悬停时滚动条宽度无法扩展,出现scrollbar.addEventListener报错

错误原因分析
  • ::-webkit-scrollbar是CSS伪元素,不是真实存在的DOM节点,document.querySelector无法获取到它的引用,因此scrollbar变量的值为null。对null调用addEventListener方法,就会触发addEventListener is not a function的报错。
正确实现方案

方案一:纯CSS实现(推荐)

直接通过CSS的:hover伪类关联容器与滚动条样式,代码简洁且兼容性更好:

/* 默认滚动条宽度 */
.articles-container::-webkit-scrollbar {
  width: 20px;
  transition: width 0.2s ease; /* 添加过渡动画让宽度变化更流畅 */
}

/* 容器 hover 时的滚动条宽度 */
.articles-container:hover::-webkit-scrollbar {
  width: 30px;
}

方案二:JS辅助实现(不推荐,仅作备选)

由于无法直接操作滚动条伪元素,可通过监听容器的鼠标事件,给容器添加/移除类来间接控制滚动条样式:

.articles-container::-webkit-scrollbar {
  width: 20px;
  transition: width 0.2s ease;
}

/* 自定义类控制滚动条宽度 */
.articles-container.scrollbar-wide::-webkit-scrollbar {
  width: 30px;
}
setTimeout(function() {
  const container = document.querySelector('.articles-container');
  if (!container) return; // 先判断容器是否存在,避免后续报错

  function scon() {
    container.classList.add('scrollbar-wide');
  }

  function scout() {
    container.classList.remove('scrollbar-wide');
  }

  container.addEventListener('mouseover', scon, false);
  container.addEventListener('mouseout', scout, false);
}, 1300);

内容的提问来源于stack exchange,提问作者Soumya Roy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:24:27