html部分
拖动滑块,用到的知识点
- 在barBox上添加事件, pointer-events: none;//不接受鼠标事件 可以添加音量控制,进度控制
- JS获取标签的宽度:xx.offsetWidth
高度就是:xx.offsetHeight
- 把mousemove写在document上,保证事件在页面中任何位置都有效。包括在标签外。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="css/huakuai.css">
</head>
<body>
<div class="barBox" id="barBox">
<div class="barColor" id="barColor"></div>
<div class="barBlock" id="barBlock"></div>
</div>
<script src="js/huakuai.js"></script>
</body>
</html>
css部分
.barBox{
margin: 100px;
height: 30px;
width: 200px;
background: #eee;
position: relative;
}
.barColor{
background: #5ac3ff;
height: 30px;
width: 50%;
float: left;
}
.barBlock{
width: 20px;
height: 40px;
background: #346a8e;
position: absolute;
left:50%;
margin-left: -10px;
top: -5px;
pointer-events: none;/*不接受鼠标事件 */
}
js部分
{
let barBox = document.getElementById("barBox");
let barColor = document.getElementById("barColor"); // 色块
let barBlock = document.getElementById("barBlock"); // 小方块
let barColor_startWdith = 100; // 色块初始的宽度
let barBlock_startLeft = 100 ; // 小方块初始的left值
let startX ; // 鼠标开始按下的位置
let mMove = function(event){
event.preventDefault(); // 阻止默认事件
let mouseX = event.clientX; // 鼠标的在窗口的位置
let dis = mouseX - startX ; // 计算鼠标在窗口的移动距离
let disWidth = barColor_startWdith + dis ; // 色块跟随鼠标走的宽度:当前宽度+移动距离
if( disWidth > 200 ){ // 如果色块的宽度大于了最大值 200
disWidth = 200;
}
// 色块的宽度不能为负数
if(disWidth<0){
disWidth = 0;
}
barColor.style.width = disWidth + "px";
barBlock.style.left = disWidth + "px";
// 控制音量之类的,可以用 disWidth的值参与运算。此处略
console.info( "dis:"+ dis );
console.info( "barColor.offsetWdith:"+ barColor.offsetWidth );
};
barBox.addEventListener("mousedown",function(event){
event.preventDefault(); // 阻止默认事件
startX = event.clientX ; // 记录鼠标点下的开始x坐标(相对于窗口)
// 鼠标滑动,写在页面上的。
let mx = event.offsetX;//
barColor.style.width = mx + "px";//更新色块位置
barBlock.style.left = mx + "px";//更新小方块位置
barColor_startWdith = mx;//更新色块初始的宽度
document.addEventListener("mousemove", mMove);
});
document.addEventListener("mouseup",function(event){
barColor_startWdith = barColor.offsetWidth; // 松开鼠标后,记录当前色块的宽度。
document.removeEventListener("mousemove", mMove);
});
}