一、template
<template>
<div class="slider-container" ref="slider">
<div class="slider-track" :style="{background: `linear-gradient(to right, #ccc ${ leftThumbValue }%, #D01117 ${ leftThumbValue }%, #D01117 ${ rightThumbValue }%, #ccc ${ rightThumbValue }%)`}"></div>
<span class="slider-thumb" :style="{ left: leftThumbValue + '%' }" @mousedown="activateThumb('left')">
{{ leftValue }}
</span>
<span class="slider-thumb" :style="{ left: rightThumbValue + '%' }" @mousedown="activateThumb('right')">
{{ rightValue }}
</span>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
export default defineComponent({
name: 'DoubleSlider',
props: {
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: 100
},
leftValue: {
type: Number,
default: 25
},
rightValue: {
type: Number,
default: 75
}
},
setup(props, {emit}) {
const slider = ref<HTMLElement | null>(null);
const leftThumbValue = computed(() => {
return ((props.leftValue - props.min) / (props.max - props.min)) * 100;
});
const rightThumbValue = computed(() => {
return ((props.rightValue - props.min) / (props.max - props.min)) * 100;
});
const activateThumb = (thumb: 'left' | 'right') => {
const onMouseMove = (event: MouseEvent) => {
const sliderRect = slider.value!.getBoundingClientRect();
const newLeftValue = ((event.clientX - sliderRect.left) / sliderRect.width) * 100;
const newValue = Math.round((newLeftValue / 100) * (props.max - props.min) + props.min);
if (thumb === 'left' && newValue < props.rightValue && newValue >= props.min) {
emit('change', { leftValue: newValue })
} else if (thumb === 'right' && newValue > props.leftValue && newValue <= props.max) {
emit('change', { rightValue: newValue })
}
};
const deactivateThumb = () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', deactivateThumb);
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', deactivateThumb);
};
return {
leftThumbValue,
rightThumbValue,
activateThumb,
slider,
};
}
});
</script>
<style lang="less" scoped>
@import './index.less';
</style>
二感猛、樣式
@import "@/common.less";
.slider-container {
position: relative;
width: 300px;
padding: 0 15px;
}
.slider-track {
position: absolute;
height: 5px;
border-radius: 5px;
width: 100%;
top: 0;
}
.slider-thumb {
position: absolute;
background-color: #E9302D;
border: 0;
color: #fff;
display: inline-block;
line-height: 1;
padding: 4px 12px;
top: -8px;
font-size: 12px;
margin-left: -12.5px;
border-radius: 20px;
cursor: pointer;
user-select: none;
}
三、案例
<Slider :min="600" :max="750" :left-value="leftValue" :right-value="rightValue" @change="changeSlider" />