纯JS自定义网页滚动条

最近在公司很忙,没什么时间更新,忙中抽时间做了一个JS滚动条,因为火狐浏览器与谷歌浏览器的滚动条自定义样式过于麻烦,所以我打算自己写个方便改样式的滚动条

css

<style>
#CheShi {
background: #ccc;
width: 80%;
height: 200px;
overflow: hidden;
position: relative;
/* 禁止选择文字 */
moz-user-select: -moz-none;
-moz-user-select: none;
-o-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
}
#CheShi_ul {
margin: 0px;
padding: 0px;
position: absolute;
top: 0px;
left: 0px;
}
</style>

html

<div id="CheShi">
<ul id="CheShi_ul">
<li>测试(Start)</li>
<li>测试1</li>
<li>测试2</li>
<li>测试3</li>
<li>测试4</li>
<li>测试5</li>
<li>测试</li>
<li>测试</li>
<li>测试</li>
<li>测试</li>
<li>测试</li>
<li>测试</li>
<li>测试</li>
<li>测试</li>
<li>测试</li>
<li>测试(END)</li>
</ul>
</div>

js

//生成滚动条
document.querySelectorAll("#CheShi")[0].innerHTML +=
'<div id="Y_CustomScrollBar" style="height:100%;width:30px;position: absolute;right: 0px;top:0px;background:#666"><span style="width:80%;height: 50px;background:#999;display: block;border-radius: 10px;transform: translateX(-50%);position: absolute;left: 50%;top: 0px;"></span></div>';
var CheShi = document.querySelectorAll("#CheShi")[0];
var CheShiU = document.querySelectorAll("#CheShi #CheShi_ul")[0];
var Y_CustomScrollBar_span = document.querySelectorAll("#Y_CustomScrollBar span")[0];
var CheShiH = CheShi.offsetHeight; //200
var CheShiUH = CheShiU.offsetHeight; //441
var XJValue = CheShiUH - CheShiH; //241
var XJValue2 = CheShiH - XJValue; //-41
var ExtraHeight = 0;
var DownY = 0;
var DownB = false;
//设置滚动条的高度
if (XJValue2 > 50 && XJValue2 < CheShiH) {
Y_CustomScrollBar_span.style.height = XJValue2 + "px";
} else if (XJValue2 < 50) {
ExtraHeight = XJValue2 - 50;
Y_CustomScrollBar_span.style.height = 50 + "px";
} else {
document.querySelectorAll("#Y_CustomScrollBar")[0].style.display = "none"
}
//计算鼠标偏移
Y_CustomScrollBar_span.onmousedown = function(e1) {
DownY = e1.offsetY;
DownB = true;
}
Y_CustomScrollBar_span.onmouseup = function(e1) {
DownB = false;
}
Y_CustomScrollBar_span.onmousemove = function(e2) {
if (DownB == true) {
//滚动条
if (((e2.clientY - DownY)) >= 0 && ((e2.clientY - DownY)) <= CheShiH - parseInt(Y_CustomScrollBar_span.style.height)) {
Y_CustomScrollBar_span.style.top = "" + (e2.clientY - DownY) + "px";
}
//滚动内容
CheShi_ul.style.top = -(parseInt(Y_CustomScrollBar_span.style.top) * ((CheShiUH - CheShiH) / (CheShiH - parseInt(Y_CustomScrollBar_span.style.height)))) + "px"
}
}

效果


  LRolinx  阅读(152)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示