目标
滑块拖动数字,从0~100
遇到的问题
- 监听主体绑定错误,绑定到了滑块元素上了,导致鼠标移开的时候,再左右移动滑块不会再动了
- 滑块到达100%的时候,会溢出长度了。解决方案是 给滑块(两层结构,给子元素)添加个translateX为-50%
代码
<div class="track-box">
<div class="track-bg"></div>
<div class="track-active" :style="{ width: sensitiveLeft + '%' }"></div>
<div class="track-ball" :style="{ left: sensitiveLeft + '%' }">
<div class="track-ball-btn"></div>
</div>
</div>
<div class="right-values">{{ parseInt(sensitiveLeft) }}</div>
.track-box {
width: 21.77vw;
position: relative;
.track-bg {
width: 100%;
height: 0.55vh;
border: 0.01vw solid rgba(255, 255, 255, 0.5);
border-radius: 0.16rem;
position: relative;
z-index: 10;
}
.track-active {
width: 10%;
height: 0.55vh;
background: #6F6F6F;
border: 0.01vw solid #6F6F6F;
position: absolute;
left: 0;
top: 0;
z-index: 10;
}
.track-ball {
width: 2.04vh;
height: 2.04vh;
position: absolute;
left: 10%;
top: -0.745vh;
z-index: 10;
cursor: pointer;
.track-ball-btn {
width: 2.04vh;
height: 2.04vh;
border-radius: 50%;
background: #6F6F6F;
transform: translateX(-50%);
}
}
}
.right-values {
width: 2vw;
}
handleCameraSetListen() {
let objEle = document.getElementsByClassName('track-ball')[0];
objEle.onmousedown = e => {
let e_mousedown = e || window.event; //要用event这个对象来获取鼠标的位置
e_mousedown.preventDefault();
var x = e_mousedown.clientX - objEle.offsetLeft;
// console.log('mousedown', e_mousedown.clientX, objEle.offsetLeft, x);
this.sensitiveFlag = true;
document.onmousemove = e => {
let e_mousemove = e || window.event; //要用event这个对象来获取鼠标的位置
e_mousemove.preventDefault();
if (!this.sensitiveFlag) {
return;
}
this.sensitiveLeft =
((e_mousemove.clientX - x) / (objEle.offsetParent.offsetWidth - objEle.offsetWidth)) * 100;
if (this.sensitiveLeft <= 0) {
this.sensitiveLeft = 0;
} else if (this.sensitiveLeft >= 100) {
this.sensitiveLeft = 100;
}
console.log( 'mousemove', event.clientX, x,objEle.offsetWidth,objEle.offsetParent.offsetWidth, this.sensitiveLeft);
};
document.onmouseup = e => {
let e_mouseup = e || window.event; //要用event这个对象来获取鼠标的位置
e_mouseup.preventDefault();
this.sensitiveFlag = false;
console.log('mouseup', this.sensitiveFlag);
};
};
}
// 优化
watch: {
cameraModalShow(newVal) {
if(!newVal) {
document.onmousemove = null;
document.onmouseup = null;
} else {
this.$nextTick(() => {
this.handleCameraSetListen();
});
}
}
}