原生js实现自定义滚动条
<div class="wrap"> <div class="content"></div> <div class="scroll"> <div class="bar"></div> </div> </div>
* { margin: 0; padding: 0; user-select: none; } .wrap { overflow: hidden; position: relative; width: 400px; height: 600px; background-color: #f1f1f1; margin: 10px auto; box-shadow: 0 0 10px red; } .content { position: absolute; left: 0; top: 0; width: 380px; padding: 10px; line-height: 30px; text-indent: 2em; } .scroll { position: absolute; top: 0; right: 0; width: 16px; height: 600px; background-color: #ccc; } .bar { position: absolute; width: 16px; border-radius: 10px; background-color: #333; }
var oWrap = document.querySelector('.wrap'); var oContent = document.querySelector('.content'); var oScroll = document.querySelector('.scroll'); var oBar = document.querySelector('.bar'); var rate = 0; //初始函数 initSCroll(); function initSCroll() { //初始bar的高度; oBar.style.height = oWrap.offsetHeight / oContent.offsetHeight * oScroll.offsetHeight + 'px'; //内容展示比例 rate = (oContent.offsetHeight - oWrap.offsetHeight) / (oScroll.offsetHeight - oBar.offsetHeight); }; var eventTypeMap = { isDown: false, startPos: { y: 0, top: 0 }, 'mousedown': function(e) { this.isDown = true; this.startPos.y = e.clientY; this.startPos.top = oBar.offsetTop; }, 'mousemove': function(e) { if (!this.isDown) { return false; } var _y = e.clientY - this.startPos.y + this.startPos.top; scrollBar(_y); }, 'mouseup': function(e) { if (!this.isDown) { return false; } this.isDown = false; }, 'mousewheel': function(e) { var _y = oBar.offsetTop; if (e.wheelDelta > 0) { _y -= 10; } else { _y += 10; } scrollBar(_y); } }; //事件 oBar.addEventListener('mousedown', eventSort, false); document.addEventListener('mousemove', eventSort, false); document.addEventListener('mouseup', eventSort, false); oBar.addEventListener('mousewheel', eventSort, false); //事件分流 function eventSort(e) { if (eventTypeMap[e.type] && typeof eventTypeMap[e.type] === 'function') { eventTypeMap[e.type](e); } }; function scrollBar(_y) { _y = Math.max(0, _y); _y = Math.min(_y, oScroll.offsetHeight - oBar.offsetHeight); oBar.style.top = _y + 'px'; oContent.style.marginTop = -_y * rate + 'px'; }