简单的滑动条拖拽效果,
如果有什么错误,请多多指教
<style>
* {
margin: 0;
padding: 0;
user-select: none; //禁止用户选中
}
.box {
width: 500px;
height: 20px;
box-shadow: 0 0 1px #0000FF;
border-radius: 10px;
float: left;
position: relative;
margin-top: 100px;
}
span {
display: block;
width: 20px;
height: 20px;
box-shadow: 0 0 1px #0000FF;
float: left;
margin-top: 100px;
margin-left: 100px;
text-align: center;
}
p {
width: 20px;
height: 20px;
float: left;
margin-top: 100px;
text-align: center;
}
.button {
width: 20px;
height: 40px;
background-color: #555555;
position: absolute;
left: 0;
top: -10px;
border-radius: 20px;
}
.se{
height:100%;position: absolute;border-radius:10px 0 0 10px ;
}
</style>
</head>
<body>
<span>0</span>
<p>0</p>
<div class="box">
<div class="se"></div>
<div class="button"></div>
</div>
<p>10</p>
</body>
<script>
var obutton = document.querySelector(".button");
var ospan = document.querySelector("span");
var obox = document.querySelector(".box");
var ose = document.querySelector(".se");
var start;
var target = obox.offsetWidth - ospan.offsetWidth; // 滑动条最大能移动的距离
obutton.onmousedown = function(eve) {
var e1 = eve || window.event;
//当鼠标按下时, 定义变量start的值为鼠标按下时的clientX
if (start == undefined) start = e1.clientX;
document.onmousemove = function(eve) {
var e2 = eve || window.event;
// 移动的距离 = 鼠标移动的距离 - 鼠标按下时的位置
var l = e2.clientX - start;
// 当移动的距离大于能滑动的最大距离,直接设置为最大距离。
if (l > target) l = target;
// 当移动的距离小于0时,直接设置为最小值0
if (l < 0) l = 0;
obutton.style.left = l + "px";
// console.log(l);
var jindu = ((l / target) * 10).toFixed(1); //转换成一位小数
if(jindu == 0.0){
jindu = 0;
}else if(jindu == 10.0){
jindu = 10;
}
ospan.innerHTML = jindu;
//设置se的宽度为移动的宽度,
ose.style.width = l + "px";
ose.style.backgroundColor = "#555555";//上色
}
// 松开鼠标 ,移动事件失效
document.onmouseup = function() {
document.onmousemove = null;
}
}
</script>
下方为效果图