我想将滚动条宽度更改得更宽,以便当用户将鼠标悬停在其上时看起来很清楚。
所以我写道:
::-webkit-scrollbar {
width: 7px;
height: 7px;
background-color: #ddd;
}
::-webkit-scrollbar:hover {
width: 10px;
height: 10px;
background-color: red;
}
背景颜色变为红色,但宽度不变,有没有办法解决这个问题?这是 plnkr
使用 border
而不是 width
来实现这一点:
::-webkit-scrollbar {
width: 7px;
height: 7px;
}
::-webkit-scrollbar-thumb {
background: #ababab;
border-radius: 10px;
border: 2px solid transparent;
background-clip: padding-box; // <== make the border work
}
::-webkit-scrollbar-thumb:hover{
border: 0;
}
::-webkit-scrollbar-track {
background: transparent;
}
*:hover::-webkit-scrollbar {
width: 10px;
height: 10px;
}
这将更改任何元素滚动条的宽度和高度。如果您想更具体,只需将"*"交换到您选择的选择器即可。例如,要将其应用于具有"my-custom-scrollbar"类的元素的滚动条:
.my-custom-scrollbar:hover::-webkit-scrollbar {
width: 10px;
height: 10px;
}
使用mousemove事件使用的解决方法:
document.addEventListener("mousemove", function(e){
let ele = document.getElementById('element');
let distance = ele.offsetLeft + ele.offsetWidth - e.pageX;
distance < 15 && distance > -15 ? ele.classList.add('more-width') : ele.classList.remove('more-width');
});
和样式将是
#element::-webkit-scrollbar-thumb {
background: #888;
}
#element::-webkit-scrollbar {
width: 5px;
}
#element.more-width::-webkit-scrollbar {
width: 10px;
}
代码笔示例:https://codepen.io/KhaleD_D/pen/OJpgJKM
此解决方案使用本机为 16px 大的滚动条,但我们仅显示 6px 以使其更薄(并为内容留出更多空间(。但诀窍是overflow: overlay
它允许内容即使在滚动条区域上显示。
使用这种方法,您可以获得细滚动条,该滚动条在悬停时会放大(悬停有点宽(。
我受到Khaled解决方案的启发,但我只使用CSS方法:
.custom-scrollbar {
scrollbar-color: var(--gray) var(--secondary);
scrollbar-width: thin;
overflow: overlay !important;
}
.custom-scrollbar::-webkit-scrollbar {
width: 16px;
height: 16px;
background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-track-piece {
background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb:vertical {
background: linear-gradient(to left, var(--gray) 6px, transparent 0%);
}
.custom-scrollbar::-webkit-scrollbar-thumb:horizontal {
background: linear-gradient(to bottom, var(--gray) 6px, transparent 0%);
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: var(--gray);
}
我使用以下代码来实现悬停时增加宽度的效果。可悲的是,它仅适用于Chrome和Edge。对于格式不正确,我深表歉意。
* {
&::-webkit-scrollbar-thumb {
border: 5px solid transparent;
border-radius: 10px;
background-color: grey;
background-clip: content-box;
-webkit-background-clip: content-box;
}
&::-webkit-scrollbar-thumb:hover {
background-color: black;
background-clip: border-box;
-webkit-background-clip: border-box;
}
&::-webkit-scrollbar {
width: 16px;
height: 16px;
background-color: transparent;
}
}