<template>
<div class="about">
<div class="box">
<!-- 默认线 -->
<div class="Line"></div>
<!-- 蓝色的线 -->
<div class="slider-Line" ref="slider-Line"></div>
<!-- 左边小球 -->
<div class="ball" @touchstart.prevent="fnstart"></div>
<!-- 右边小球 -->
<div class="ball ac" @touchstart.prevent="fnstart"></div>
<!-- 上面的数字 -->
<div class="num" ref="num">{{ num }}</div>
</div>
</div>
</template>
js
<script>
export default {
data() {
return {
num: 0,
};
},
methods: {
fnstart(ev) {
// 小球
this.oDiv = ev.target;
// pagx:鼠标点击的位置到页面最左边的距离 offsetLeft当前元素左边到最大盒子最左边
this.pageX = ev.changedTouches[0].pageX - this.oDiv.offsetLeft;
document.ontouchmove = this.FnMove;
document.ontouchend = this.FnEnd;
// 父元素的宽度
this.parent = ev.target.parentNode.offsetWidth;
// 减去小球的宽度
this.Width = this.parent - ev.target.offsetWidth;
//获取父元素
this.parents = ev.target.parentNode;
//获取子元素
this.child = this.parents.children;
// 右边小球 获取小球
this.Right = this.parents.children[0];
// 左边小球
this.Left = this.parents.children[1];
},
FnMove(ev) {
// 减去小球滑动的距离 计算的是元素最左边,到浏览器最边上
this.X = ev.changedTouches[0].pageX - this.pageX;
// console.log(this.X, 1010101);
// 判断小球等于零不能出去
if (this.X <= 0) {
this.X = 0;
}
// 判断大于等于不让球出去
if (this.X > this.Width) {
this.X = this.Width;
}
// 让左边小球滑动,线跟着换颜色
//滑动上面的数值跟着变,分成100份
this.xnum = this.X / 3.7;
// 取整数
this.num = parseInt(this.xnum);
this.$refs["num"].style.left = this.X + 6 + "px";
// 让小球相交不影响
// 动态监测左右
for (var i = 0; i < this.child.length; i++) {
if (this.child[i].classList.contains("ball")) {
// 一共5个元素 减掉3就是 蓝色线条的位置 length
let Len = this.child.length - 3;
if (i == Len) {
// 左边小球减右边小球取绝对值就是线条的宽
this.dis = Math.abs( this.child[i].offsetLeft - this.child[i + 1].offsetLeft );
// 小球的宽度
this.child[1].style.width = this.dis + "px";
// 如果左边小球减掉右边小球的值小于0 蓝色线条的left就是左边小球的offsetLeft值
if (this.child[i].offsetLeft - this.child[i + 1].offsetLeft < 0) {
this.child[1].style.left = this.child[i].offsetLeft + "px";
} else {
// 否则就是右边小球的offsetLeft值
this.child[1].style.left = this.child[i + 1].offsetLeft + "px";
}
}
}
}
this.oDiv.style.left = this.X + "px";
},
FnEnd() {
document.ontouchmove = null;
document.ontouchend = null;
},
},
};
</script>
css
<style lang="less" scoped>
.box {
position: relative;
width: 400px;
height: 30px;
background-color: rgb(240, 16, 83);
top: 50px;
margin: auto;
.ball {
position: absolute;
width: 30px;
height: 30px;
background-color: pink;
border-radius: 50%;
z-index: 2;
}
.ball.ac {
right: 0;
background-color: purple;
}
.Line {
position: absolute;
top: 14px;
width: 400px;
height: 2px;
line-height: 30px;
background: #ccc;
}
.slider-Line {
position: absolute;
top: 14px;
width: 400px;
height: 2px;
line-height: 30px;
background-color: blue;
}
.num {
position: absolute;
top: -19px;
left: 9px;
}
}
</style>