Loading

纯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"
				}
			}

效果


posted @ 2019-08-19 16:04  LRolinx  阅读(145)  评论(0编辑  收藏  举报