自定义滚动条轨道上下箭头缺失问题求助
解决自定义WebKit滚动条上下箭头缺失的问题
嘿,我懂你现在的困扰——自定义了滚动条样式后,原本轨道两端的上下箭头不见了对吧?其实这是因为WebKit滚动条的箭头是独立的伪元素,默认情况下,当你只定义了scrollbar、scrollbar-track和scrollbar-thumb时,箭头按钮(scrollbar-button)会被隐藏或者继承了不显示的样式,所以得专门给它加样式才行。
问题根源
WebKit滚动条的结构包含几个核心伪元素:
::-webkit-scrollbar:整个滚动条的容器::-webkit-scrollbar-track:滚动条的轨道区域::-webkit-scrollbar-thumb:滚动条的滑块::-webkit-scrollbar-button:轨道两端的上下箭头按钮(这就是你缺失的部分)
默认情况下,如果你没有显式设置scrollbar-button的样式,它可能会被隐藏,或者样式被你的自定义轨道覆盖。
解决方案:添加箭头按钮的样式
我们需要给::-webkit-scrollbar-button设置样式,包括正常状态、hover状态,还要用CSS绘制箭头(或者用背景图)。下面是调整后的完整代码:
div{ max-width:150px; max-height:200px; overflow-y: scroll; overflow-x: hidden; border: 1px solid #ccc; /* 加个边框方便看效果 */ } /* 整个滚动条容器 */ div::-webkit-scrollbar { width: 1.2em; } /* 滚动条轨道 */ div::-webkit-scrollbar-track { background: #f1f1f1; -webkit-box-shadow: inset 0 0 2px rgba(0,0,0,0.1); } /* 滚动条滑块 */ div::-webkit-scrollbar-thumb { background-color: darkgrey; outline: 1px solid slategrey; border-radius: 4px; } /* 滚动条上下箭头按钮 */ div::-webkit-scrollbar-button { background-color: #f1f1f1; border: 1px solid #ccc; height: 16px; width: 100%; position: relative; } /* 上箭头 */ div::-webkit-scrollbar-button:single-button:vertical:decrement::before { content: ''; position: absolute; top: 3px; left: 50%; transform: translateX(-50%); border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 5px solid #666; } /* 下箭头 */ div::-webkit-scrollbar-button:single-button:vertical:increment::before { content: ''; position: absolute; bottom: 3px; left: 50%; transform: translateX(-50%); border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #666; } /* 箭头hover状态 */ div::-webkit-scrollbar-button:hover { background-color: #e1e1e1; } div::-webkit-scrollbar-button:hover::before { border-bottom-color: #333; /* 上箭头hover变色 */ border-top-color: #333; /* 下箭头hover变色 */ }
<div> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div>
代码说明
::-webkit-scrollbar-button:设置按钮的基础样式(背景、边框、尺寸)- 用
:single-button:vertical:decrement和:single-button:vertical:increment分别定位上下箭头按钮 - 通过伪元素
::before用CSS边框绘制箭头,替代图片更灵活 - 添加hover状态让交互更友好
这样调整后,滚动条轨道的上下箭头就会显示出来,和你期望的效果一致啦!
内容的提问来源于stack exchange,提问作者Mona Coder
相关产品推荐
相关产品推荐

