js手写滚动条
效果图
HTML
<!--进度条-->
<div class="bar">
<div class="progress">
<div id="oDiv" class="circle"></div>
</div>
</div>
css
html, body {
background-color: #f1f1f1;
}
.bar {
width: 600px;
height: 8px;
background-color: #5A5A5A;
margin: 200px auto;
position: relative;
}
.progress {
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 0px;
background-color: dodgerblue;
}
.circle {
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
position: absolute;
top: -5px;
left: -10px;
}
js代码
dragFn('oDiv', 600, 10)//设置可拖拽元素
/*
* params id
* params max 最大长度
* params r 半径
* */
function dragFn(id, max ,r) {
var oDiv = document.getElementById(id);
var disX = 0, disY = 0;
oDiv.onmousedown = function (ev) {
var oEvent = ev || event;
disX = oEvent.clientX - oDiv.offsetLeft;
disY = oEvent.clientY - oDiv.offsetTop;
document.onmousemove = function (ev) {
var oEvent = ev || event;
var l = oEvent.clientX - disX;
var t = oEvent.clientY - disY;
if (l >= max) {
l = max - r
}
console.log(l);
if (l <= 0) {
l = 0
}
if (t < 0) {
t = 0
}
if (l > document.documentElement.clientWidth - oDiv.offsetWidth) {
l = document.documentElement.clientWidth - oDiv.offsetWidth;
}
if (t > document.documentElement.clientHeight - oDiv.offsetHeight) {
t = document.documentElement.clientHeight - oDiv.offsetHeight;
}
oDiv.style.left = l + 'px';
// oDiv.style.top = t + 'px';
}
document.onmouseup = function (ev) {
document.onmousemove = null;
document.onmouseup = null;
}
}
}
记
可根据具体位置播放对应内容