vue封装滑块

使用:

//滑块 (滑动选择器)

//引用后直接使用

<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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值