HTML代码
<!-- 滚动条 -->
<div class="progress_bar" id="progress_bar">
<!-- 红线 -->
<div class="red_line"></div>
<!-- 小球 -->
<div class="ball" id="ball"></div>
</div>
CSS代码
<style>
/* 滚动条样式 */
.progress_bar {
margin-top: 19px;
width: 592px;
height: 3px;
border-radius: 5px;
position: relative;
}
/* 小球样式 */
.progress_bar .ball {
width: 24px;
height: 24px;
border-radius: 24px;
background: #ff4600;
position: absolute;
top: 50%;
left: 26px;
transform: translatey(-50%);
animation: animate-positive2 0.5s;
cursor: pointer;
}
/* 红线样式 */
.progress_bar .red_line {
width: 26px;
height: 3px;
background: #ff4600;
border-radius: 5px;
animation: animate-positive 0.5s;
}
/* 动画 */
@-webkit-keyframes animate-positive {
0% {
width: 0%;
}
}
@keyframes animate-positive {
0% {
width: 0%;
}
}
@-webkit-keyframes animate-positive2 {
0% {
left: 0%;
}
}
@keyframes animate-positive2 {
0% {
left: 0%;
}
}
</style>
JS代码
<script>
/**
* btn 被拖动元素
* bar 滚动条
* title 暂时不用
* **/
let scale = function (btn, bar, title) {
this.btn = document.getElementById(btn);//小球
this.bar = document.getElementById(bar);//滚动条
this.title = document.getElementById(title);
this.step = this.bar.getElementsByTagName("DIV")[0];//滚动条上的红线
this.init();
};
scale.prototype = {
init: function () {
var f = this, g = document, b = window, m = Math;
f.btn.onmousedown = function (e) {//小球的鼠标按下事件
var x = (e || b.event).clientX;//获取小球的距离屏幕左侧的距离
console.log('小球的clientX', x);
var l = this.offsetLeft;// 获取小球到滚动条左侧的距离
var max = f.bar.offsetWidth - this.offsetWidth;// 滚动条的宽度减去小球的宽度之后剩下的距离
g.onmousemove = function (e) {
var thisX = (e || b.event).clientX;// 获取鼠标距离屏幕左侧的距离
var to = m.min(max, m.max(-2, l + (thisX - x)));
f.btn.style.left = to + 'px';
f.ondrag(m.round(m.max(0, to / max) * 100), to);
b.getSelection ? b.getSelection().removeAllRanges() : g.selection.empty();
};
g.onmouseup = new Function('this.onmousemove=null');
};
},
ondrag: function (pos, x) {
this.step.style.width = Math.max(0, x) + 'px';
}
}
// 参数1:小球,参数2:父元素,
new scale('ball', 'progress_bar', 'refer_title');
</script>
效果图