JSFiddle - React, Tailwind, and code Playground
by 智翔
HTML
<div class="scrollbar">
<div class="scrollbar-content">
<ul class="box">
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
<li>11111</li>
</ul>
</div>
<div class='scrollbar-bar'>
<div ref="thumb" class="scrollbar-thumb"></div>
</div>
</div>
<button id="add">增加li</button>
<button id="del">删除li</button>
CSS
*{margin:0;padding:0;list-style: none;}
.scrollbar{
position: relative;
}
.scrollbar-bar{
position: absolute;
right: 2px;
bottom: 2px;
z-index: 1;
width: 6px;
height: 100%;
border-radius: 4px;
opacity: 0;
transition: opacity 120ms ease-out;
}
.scrollbar-thumb {
position: relative;
display: block;
width: 100%;
height: 0;
border-radius: inherit;
background-color: rgba(135,141,153,.3);
transition: .3s background-color;
cursor: pointer;
}
.scrollbar:hover .scrollbar-bar{
opacity: 1;
transition: opacity 340ms ease-out;
}
.box{ height: 400px; overflow: auto; }
li{ line-height: 46px; height: 46px; }
JavaScript
let wrap = document.getElementsByClassName("box")[0];
let bar = document.getElementsByClassName("scrollbar-bar")[0];
let thumb = document.getElementsByClassName("scrollbar-thumb")[0];
let gutter = getScrollWidth();{}
if(gutter){wrap.style.marginRight = `-${gutter}px`};
updateThumb()
function getScrollWidth(){
const outer = document.createElement("div");
outer.style.width = '100px';
outer.style.visibility = "hidden";
outer.style.position = "absolute";
outer.style.top = "-9999px";
document.body.appendChild(outer);
const widthNoScroll = outer.offsetWidth;
outer.style.overflow = "scroll";
const inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
const widthWithScroll = inner.offsetWidth;
outer.parentNode.removeChild(outer);
scrollBarWidth = widthNoScroll - widthWithScroll;
return scrollBarWidth;
}
function updateThumb(){
let heightPercentage = (wrap.clientHeight * 100 / wrap.scrollHeight);
thumb.style.height = heightPercentage + "%";
}