使用:
//滑块 (滑动选择器)
//引用后直接使用
<script setup>
import { ref,onMounted,onBeforeUnmount} from 'vue';
const value=ref(20)
//引用
const target = ref(null) //小圆按钮
const targetline = ref(null)//线条
//点击进度条
const up = (e) => {
let x = e.clientX-targetline.value.offsetLeft //点击横线为位置(鼠标点击在页面的位置-线条左边距离页面的宽度)
let linewidth=targetline.value.offsetWidth//选择横线的长度:
value.value=Math.ceil((x/linewidth)*100)
}
//拖动小圆按钮
const mousedown = () => {
window.addEventListener('mousemove', mousemove)
}
const mousemove = (e) => {
let x = e.clientX-targetline.value.offsetLeft //点击横线为位置(鼠标点击在页面的位置-线条左边距离页面的宽度)
let linewidth=targetline.value.offsetWidth//选择横线的长度:
value.value=Math.ceil((x/linewidth)*100)
}
const mouseup = () => {
window.removeEventListener('mousemove', mousemove)
}
//绑定解绑点击事件
onMounted(() => {
targetline.value.addEventListener('click', up)
target.value.addEventListener('mousedown', mousedown)
window.addEventListener('mouseup', mouseup)
})
onBeforeUnmount(() => {
targetline.value.removeEventListener('click', up)
target.value.removeEventListener('mousedown', mousedown)
window.removeEventListener('mouseup', mouseup)
})
//鼠标按压事件给小圆按钮绑定,鼠标移动事件与离开事件给window绑定L:
//这样点击按钮才触发时间,且当鼠标移动到父元素(线条)外面时,仍然可以移动小圆按钮实现拖动且解绑事件
</script>
<template>
<div class="main">
<div class="slider" @click="clickposition" ref="targetline">
<div class="left" :style="{width: value + '%'}" ></div>
<div class="button" :style="{left: value + '%'}" ref="target"></div>
<div class="right" :style="{width: 100-value + '%'}" ></div>
</div>
<div>
<el-input-number v-model="value" :min="1" :max="100" />
</div>
</div>
</template>
<style scoped lang="scss">
.main{
display: flex;
.slider{
display: flex;
width: 100%;
height: 16px;
position: relative;
.left{
margin-top: 5px;
width: 50%;
height: 6px;
background-color: rgb(72, 194, 242);
}
.right{
margin-top: 5px;
width: 50%;
height: 6px;
background-color: #d1cccc;
}
.button{
position: absolute;
height: 16px;
width: 16px;
background-color: #fff;
border: 2px solid rgb(72, 194, 242);
border-radius: 100%;
left: 50%;
transform: translateX(-50%);
}
}
}
.el-input-number{
margin-left: 20px;
width: 120px;
height: 30px;
}
</style>