鼠标悬停时滚动条宽度无法扩展,出现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
相关产品推荐
相关产品推荐

