上图是效果图, 可以自己修改样式
appslider.vue
<slider :value-fun="sliderVal" :min="0" :max="100"></slider>
slidercom.vue
<div class="slider1" ref="mySlider1">
<div class="propo1"></div>
<div class="propo-bg1"></div>
<div class="right-btn1" :class="{active:myPosition1.isBtn1==1}"><p class="getnum">{{num}}%</p></div>
</div>
script:
props:{
"valueFun":{
type:Function,
required: true,
},
"max":{
type:Number,
default:100
},
"min":{
type:Number,
default:0
}
},
data(){
return{
myPosition1:{
left:0,
right:100,
now:0,
// isBtn:0,
isBtn1:1,//初始化滑块为1:right-btn
propoWidth:0
},
num:0,
myDefault1:null
}
},
mounted(){
//滑块
let that = this
let mySlider1 = this.$refs.mySlider1
let propo1 = mySlider1.children[0]
let rightBtn1 = mySlider1.children[2]
let myWidth1 = 0
const elementLeft = (e) => { //计算x坐标
var offset = e.offsetLeft;
if(e.offsetParent != null) offset += elementLeft(e.offsetParent);
return offset;
}
const myCount1 = () => { //计算滑动
this.myPosition1.propoWidth1 = this.myPosition1.left//黄色颜色条
propo1.style.width = this.myPosition1.propoWidth1+'%'//propo的style中的width
propo1.style.left = this.min//propo的style中的left
this.num = parseInt(this.myPosition1.left);
this.valueFun(parseInt(this.myPosition1.left),parseInt(this.myPosition1.right),parseInt(this.myPosition1.propoWidth1))
}
this.myDefault1 = () => {//初始化
this.myPosition1.left = this.min
if(this.max >= this.min){
this.myPosition1.propoWidth1 = this.myPosition1.left + '%'//this.max - this.min
propo1.style.left = this.myPosition1.left + '%'
}
propo1.style.width = this.myPosition1.propoWidth1+'%'
rightBtn1.style.left = this.myPosition1.left + '%'
this.valueFun(this.myPosition1.left,this.myPosition1.right,this.myPosition1.propoWidth1)
}
let mySliderX1 = elementLeft(mySlider1) //滑动块x坐标
mySlider1.addEventListener('touchmove',(e)=>{ //屏幕滑动事件
console.log('move')
let pageX = e.touches[0].pageX-mySliderX1 //获取滑动x坐标
myWidth1 = (pageX/mySlider1.offsetWidth)*100 //计算百分比--移动rigbtn时是rigbtn的left值, 移动leftbtn时是leftbtn的left值
if(myWidth1>100){ //判断不超出范围
myWidth1=100
}else if(myWidth1<0){
myWidth1=0
}
this.myPosition1.left = myWidth1//right-btn
rightBtn1.style.left = myWidth1+'%'
myCount1()
e.preventDefault()
})
mySlider1.addEventListener('touchstart',(e)=>{//屏幕触摸事件
console.log('touch')
let touchX = e.touches[0].pageX-mySliderX1
this.myPosition1.now = (touchX/mySlider1.offsetWidth)*100
mySliderX1 = elementLeft(mySlider1) //滑动块x坐标
this.myPosition1.isBtn1 = 1
})
this.myDefault1()
},
watch:{
min(New,old){
this.myDefault1()
},
max(New,old){
this.myDefault1()
}
}