效果:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>滑块</title>
<script src="https://cdn.staticfile.org/jquery/3.6.0/jquery.min.js"></script>
<style>
* {
padding: 0;
margin: 0;
}
.boxBar {
padding: 10px 0;
margin: 15px;
width: 200px;
}
.bar {
height: 6px;
background-color: #ccc;
position: relative;
cursor: pointer;
}
.slideBlock {
height: 16px;
width: 10px;
background-color: blue;
position: absolute;
top: -5px;
left: 20px;
z-index: 10;
border-radius: 3px;
cursor: pointer;
}
.track {
height: 5px;
width: 20px;
background-color: blue;
position: absolute;
top: 0;
left: 0;
}
.text {
color: blue;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="boxBar">
<div class="bar">
<div class="slideBlock"></div>
<div class="track"></div>
</div>
<p class="text">20%</p>
</div>
<script>
$('.slideBlock').mousedown(function (e) {
$('.boxBar').mousemove(function (ev) {
console.log(ev.clientX, this.offsetLeft, 'mousemove');
let left = ev.clientX - this.offsetLeft
let w = $('.bar').width()
if (left > w) left = w
if (left < 0) left = 0
$('.slideBlock').css({ 'left': left + 'px' })
$('.track').css({ 'width': left + 'px' })
$('.text').text(Math.ceil(left / w * 100) + '%')
})
document.onmouseup = function () {
$('.boxBar').off('mousemove')
}
})
// 鼠标点击轨道改变
$('.bar').click(function (ev) {
console.log(ev.clientX, this.offsetLeft);
let left = ev.clientX - this.offsetLeft
$('.slideBlock').css({ 'left': left + 'px' })
$('.track').css({ 'width': left + 'px' })
console.log(this.offsetLeft, '899');
let w = $('.bar').width()
$('.text').text(Math.ceil(left / w * 100) + '%')
})
</script>
</body>
</html>