JS原生实现滚动条
页面样式
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> * { margin: 0; padding: 0; }
.box { width: 300px; height: 500px; border: 1px solid red; margin: 100px; position: relative; overflow: hidden; }
.content { padding: 5px 18px 5px 5px; position: absolute; top: 0; left: 0;
}
.scroll { width: 18px; height: 100%; position: absolute; top: 0; right: 0; background-color: #eee; -moz-user-select:none; }
.bar { height: 100px; width: 100%; position: absolute; top: 0; left: 0; background-color: red; border-radius: 10px; cursor: pointer; } </style> </head> <body> <div class="box" id="box"> <div class="content" id="content"> 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头 床前明月光啊,明月光,疑是地上霜啊,举头嘿嘿
</div>
<div id="scroll" unselectable="on" onselectstart="return false;" style="-moz-user-select:none;" class="scroll"> <div class="bar" id="bar"></div> </div> </div>
</body> </html>
|
脚本
function my$(id) { return document.getElementById(id); }
var box = my$("box"); var content = my$("content"); var scroll = my$("scroll"); var bar = my$("bar");
var barHeight = scroll.offsetHeight * box.offsetHeight / content.offsetHeight bar.style.height = Math.floor( barHeight ) + "px"
bar.onmousedown = function(e){ var spaceY = e.clientY - bar.offsetTop document.onmousemove = function (e) { var y = e.clientY - spaceY y = y < 0 ? 0 :y y = y > scroll.offsetHeight - bar.offsetHeight ? scroll.offsetHeight - bar.offsetHeight : y, bar.style.top = y + "px" var moveY = (y/(scroll.offsetHeight - bar.offsetHeight)) * (content.offsetHeight - box.offsetHeight) content.style.marginTop = - moveY + "px" } }
document.onmouseup=function () { document.onmousemove=null; };
|
总之,需要进行多次的比例计算,以及动态的事件监听,当然可以采用JQ将方法进行更加的优化,缩短代码