效果图
完整代码
<!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>Document</title>
<style>
section {
width: 500px;
height: 30px;
background-color: red;
display: flex;
justify-content: space-around;
align-items: center;
}
div {
position: relative;
width: 90%;
height: 50%;
background-color: #ccc;
}
.jd {
position: absolute;
top: -104%;
height: 100%;
background-color: green;
}
.ball {
position: absolute;
top: -120%;
left: -10px;
height: 20px;
width: 20px;
border-radius: 50%;
background-image: radial-gradient(circle, #ccc, white, #ccc);
}
</style>
</head>
<body>
<h2>滑动滚动条</h2>
<section>
<div>
<p class="jd"></p>
<p class="ball"></p>
</div>
</section>
<script>
let section = document.querySelector("section");
let div = document.querySelector("div");
let jd = document.querySelector(".jd");
let ball = document.querySelector(".ball");
function xj(e) {
let x = e.pageX;
let y = e.pageY;
let sx = div.offsetLeft;
let sy = div.offsetTop;
let bx = x - sx;
let by = y - sy;
let ce = bx - ball.offsetWidth / 2;
if (ce < -10) {
return;
}
console.log(ce);
let divw = div.offsetWidth;
console.log(divw);
if (ce + 10 <= divw) {
ball.style.left = ce + "px";
jd.style.width = ce + 15 + "px";
}
}
section.addEventListener("mousedown", function () {
document.addEventListener("mousemove", xj);
});
document.addEventListener("mouseup", function () {
document.removeEventListener("mousemove", xj);
});
</script>
</body>
</html>