一、效果
二、代码实现
<template><div class="bar" ref="bar"><div class="slider" :style="Pos" @mousedown="mousedown"></div></div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const bar = ref<HTMLElement>();
let Pos = ref("left: 0;");
// 点击后添加事件
const mousedown = () => {window.addEventListener("mousemove", handleChange);window.addEventListener("mouseup", mouseup);
};
// 移动滑块
const handleChange = (e: any) => {if (!bar.value) return;// 获取滑块的宽度(可移动区域)let w = bar.value.clientWidth;// 获取鼠标的位置let x = e.pageX - bar.value.getBoundingClientRect().left;// 判断是否超出范围x = x < w && x > 0 ? x : x > w ? w : 0;Pos.value = `left: ${x}px;`;
};
// 鼠标放开后移除事件
const mouseup = () => {window.removeEventListener("mousemove", handleChange);window.removeEventListener("mouseup", mouseup);
};
</script>
<style scoped lang="scss">
.bar {position: relative;height: 10px;background: linear-gradient(to right, rgb(108, 58, 146), rgb(255, 0, 0));box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);width: 100%;
}
.slider {position: absolute;box-shadow: 0 0 2px rgba(0, 0, 0, 0.6);box-sizing: border-box;width: 6px;height: 100%;background-color: #fff;
}
</style>
```