纯JS自定义网页滚动条

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

CSS

<style>
			#CheShi {
				background: #ccc;
				 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

<script>
			//生成滚动条
			document.querySelectorAll("#CheShi")[0].innerHTML +=
				'<div id="Y_CustomScrollBar" style="height:100%;30px;position: absolute;right: 0px;top:0px;background:#666"><span style="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"
				}
			}
		</script>

效果
在这里插入图片描述
在这里插入图片描述

后言
本文结束了,如果觉得本技术文章对你有帮助请给我点个赞,如果有什么不足的地方,给我提意见,让我加以改进

原文地址:https://www.cnblogs.com/LRolinx/p/13850359.html