支持范围选择

This commit is contained in:
icssoa
2025-07-29 22:47:12 +08:00
parent 27bb7e36b1
commit 66759392a4
2 changed files with 159 additions and 101 deletions

View File

@@ -21,7 +21,11 @@
height: trackHeight + 'rpx'
}"
>
<view class="cl-slider__progress" :style="progressStyle"></view>
<view
class="cl-slider__progress"
:class="[pt.progress?.className]"
:style="progressStyle"
></view>
<!-- 单滑块模式 -->
<view
@@ -168,88 +172,102 @@ const trackLeft = ref<number>(0);
// 当前活动的滑块索引0: min, 1: max仅在范围模式下使用
const activeThumbIndex = ref<number>(0);
// 计算当前值的百分比(单值模式)
// 计算当前值在滑块轨道上的百分比位置(单值模式专用
const percentage = computed(() => {
if (props.range) return 0;
return ((value.value - props.min) / (props.max - props.min)) * 100;
});
// 计算范围值的百分比(范围模式)
// 计算范围模式下两个滑块的百分比位置
type RangePercentage = {
min: number;
max: number;
min: number; // 最小值滑块的位置百分比
max: number; // 最大值滑块的位置百分比
};
const rangePercentage = computed<RangePercentage>(() => {
if (!props.range) return { min: 0, max: 0 };
const val = rangeValue.value;
const minPercent = ((val[0] - props.min) / (props.max - props.min)) * 100;
const maxPercent = ((val[1] - props.min) / (props.max - props.min)) * 100;
const currentValues = rangeValue.value;
const valueRange = props.max - props.min;
// 分别计算两个滑块在轨道上的位置百分比
const minPercent = ((currentValues[0] - props.min) / valueRange) * 100;
const maxPercent = ((currentValues[1] - props.min) / valueRange) * 100;
return { min: minPercent, max: maxPercent };
});
// 进度条样式
// 计算进度条样式属性
const progressStyle = computed(() => {
const style = {};
if (props.range) {
// 范围模式:进度条从最小值滑块延伸到最大值滑块
const { min, max } = rangePercentage.value;
style["left"] = `${min}%`;
style["width"] = `${max - min}%`;
} else {
// 单值模式:进度条从轨道起点延伸到当前滑块位置
style["width"] = `${percentage.value}%`;
}
return style;
});
// 创建滑块样式通用函数
function createThumbStyle(percent: number) {
// 创建滑块的定位样式通用函数
function createThumbStyle(percentPosition: number) {
const style = {};
// 使用像素定位,确保滑块始终在轨道范围内
// 计算滑块的有效移动范围(扣除滑块自身宽度,防止超出轨道)
const effectiveTrackWidth = trackWidth.value - rpx2px(props.blockSize) + 1;
const leftPosition = (percent / 100) * effectiveTrackWidth;
const finalLeft = Math.max(0, Math.min(effectiveTrackWidth, leftPosition));
const leftPosition = (percentPosition / 100) * effectiveTrackWidth;
style["left"] = `${finalLeft}px`;
// 确保滑块位置在有效范围内
const finalLeftPosition = Math.max(0, Math.min(effectiveTrackWidth, leftPosition));
// 设置滑块的位置和尺寸
style["left"] = `${finalLeftPosition}px`;
style["width"] = `${rpx2px(props.blockSize)}px`;
style["height"] = `${rpx2px(props.blockSize)}px`;
return style;
}
// 单滑块样式
// 单值模式滑块样式
const singleThumbStyle = computed(() => {
return createThumbStyle(percentage.value);
});
// 最小值滑块样式
// 范围模式最小值滑块样式
const minThumbStyle = computed(() => {
return createThumbStyle(rangePercentage.value.min);
});
// 最大值滑块样式
// 范围模式最大值滑块样式
const maxThumbStyle = computed(() => {
return createThumbStyle(rangePercentage.value.max);
});
// 显示的值
// 计算要显示的数值文本
const displayValue = computed<string>(() => {
if (props.range) {
const val = rangeValue.value;
return `${val[0]} - ${val[1]}`;
// 范围模式:显示"最小值 - 最大值"格式
const currentValues = rangeValue.value;
return `${currentValues[0]} - ${currentValues[1]}`;
}
// 单值模式:显示当前值
return `${value.value}`;
});
// 获取滑块轨道的宽度和左边距,用于后续触摸计算
// 获取滑块轨道的位置和尺寸信息,这是触摸计算的基础数据
function getTrackInfo(): Promise<void> {
return new Promise((resolve) => {
uni.createSelectorQuery()
.in(proxy)
.select(".cl-slider__track")
.boundingClientRect((node) => {
// 保存轨道的宽度和左侧偏移量,用于后续的触摸位置计算
trackWidth.value = (node as NodeInfo).width ?? 0;
trackLeft.value = (node as NodeInfo).left ?? 0;
@@ -259,116 +277,131 @@ function getTrackInfo(): Promise<void> {
});
}
// 根据触摸点的clientX计算对应的滑块值
// 根据触摸点的横坐标计算对应的滑块
function calculateValue(clientX: number): number {
// 如果轨道宽度为0直接返回最小值
// 如果轨道宽度为0(还未初始化),直接返回最小值
if (trackWidth.value == 0) return props.min;
// 计算触摸点距离轨道左侧的偏移
const offset = clientX - trackLeft.value;
// 计算百分比限制在0~1之间
const percentage = Math.max(0, Math.min(1, offset / trackWidth.value));
// 计算值区间
const range = props.max - props.min;
// 计算实际值
let val = props.min + percentage * range;
// 计算触摸点相对于轨道左侧的偏移距离
const touchOffset = clientX - trackLeft.value;
// 按步长取整
// 将偏移距离转换为0~1的百分比并限制在有效范围内
const progressPercentage = Math.max(0, Math.min(1, touchOffset / trackWidth.value));
// 根据百分比计算在min~max范围内的实际数值
const valueRange = props.max - props.min;
let calculatedValue = props.min + progressPercentage * valueRange;
// 如果设置了步长,按步长进行取整对齐
if (props.step > 0) {
val = Math.round((val - props.min) / props.step) * props.step + props.min;
calculatedValue =
Math.round((calculatedValue - props.min) / props.step) * props.step + props.min;
}
// 限制在[min, max]区间
return Math.max(props.min, Math.min(props.max, val));
// 确保最终值在[min, max]范围内
return Math.max(props.min, Math.min(props.max, calculatedValue));
}
// 在范围模式下,确定应该移动哪个滑块
function determineActiveThumb(clientX: number) {
// 在范围模式下,根据触摸点离哪个滑块更近来确定应该移动哪个滑块
function determineActiveThumb(clientX: number): number {
if (!props.range) return 0;
const val = rangeValue.value;
const clickValue = calculateValue(clientX);
const currentValues = rangeValue.value;
const touchValue = calculateValue(clientX);
// 计算点击位置到两个滑块的距离
const distToMin = Math.abs(clickValue - val[0]);
const distToMax = Math.abs(clickValue - val[1]);
// 计算触摸位置到两个滑块的距离,选择距离更近的滑块进行操作
const distanceToMinThumb = Math.abs(touchValue - currentValues[0]);
const distanceToMaxThumb = Math.abs(touchValue - currentValues[1]);
// 选择距离更近的滑块
return distToMin <= distToMax ? 0 : 1;
// 返回距离更近的滑块索引0: 最小值滑块1: 最大值滑块)
return distanceToMinThumb <= distanceToMaxThumb ? 0 : 1;
}
// 更新滑块的值,并触发相应的事件
function updateValue(val: number | number[]) {
function updateValue(newValue: number | number[]) {
if (props.range) {
const newVal = val as number[];
const oldVal = rangeValue.value;
// 范围模式:处理双滑块
const newRangeValues = newValue as number[];
const currentRangeValues = rangeValue.value;
// 如果最小值超过了最大值交换activeThumbIndex
if (newVal[0] > newVal[1]) {
activeThumbIndex.value = activeThumbIndex.value == 0 ? 1 : 0;
// 当左滑块超过右滑块时,自动交换活动滑块索引,实现滑块角色互换
if (newRangeValues[0] > newRangeValues[1]) {
activeThumbIndex.value = 1 - activeThumbIndex.value; // 0变11变0
}
// 确保最小值不大于最大值,但允许通过拖动交换角色
const sortedVal = [Math.min(newVal[0], newVal[1]), Math.max(newVal[0], newVal[1])];
// 确保最小值始终不大于最大值,自动排序
const sortedValues = [
Math.min(newRangeValues[0], newRangeValues[1]),
Math.max(newRangeValues[0], newRangeValues[1])
];
// 检查值是否真的改变了
if (JSON.stringify(oldVal) !== JSON.stringify(sortedVal)) {
rangeValue.value = sortedVal;
emit("update:values", sortedVal);
emit("changing", sortedVal);
// 只有值真正改变时才更新和触发事件,避免不必要的渲染
if (JSON.stringify(currentRangeValues) !== JSON.stringify(sortedValues)) {
rangeValue.value = sortedValues;
emit("update:values", sortedValues);
emit("changing", sortedValues);
}
} else {
const newVal = val as number;
const oldVal = value.value;
// 单值模式:处理单个滑块
const newSingleValue = newValue as number;
const currentSingleValue = value.value;
if (oldVal !== newVal) {
value.value = newVal;
emit("update:modelValue", newVal);
emit("changing", newVal);
if (currentSingleValue !== newSingleValue) {
value.value = newSingleValue;
emit("update:modelValue", newSingleValue);
emit("changing", newSingleValue);
}
}
}
// 触摸开始事件获取轨道信息并初步设置值
// 触摸开始事件获取轨道信息并初始化滑块位置
async function onTouchStart(e: TouchEvent) {
if (props.disabled) return;
// 先获取轨道的位置和尺寸信息,这是后续计算的基础
await getTrackInfo();
// 等待DOM更新后再处理触摸逻辑
nextTick(() => {
const clientX = e.touches[0].clientX;
const newValue = calculateValue(clientX);
const calculatedValue = calculateValue(clientX);
if (props.range) {
// 范围模式:确定要操作的滑块,然后更新对应滑块的值
activeThumbIndex.value = determineActiveThumb(clientX);
const val = [...rangeValue.value];
val[activeThumbIndex.value] = newValue;
updateValue(val);
const updatedValues = [...rangeValue.value];
updatedValues[activeThumbIndex.value] = calculatedValue;
updateValue(updatedValues);
} else {
updateValue(newValue);
// 单值模式:直接更新滑块值
updateValue(calculatedValue);
}
});
}
// 触摸移动事件实时更新滑块
// 触摸移动事件实时更新滑块位置
function onTouchMove(e: TouchEvent) {
if (props.disabled) return;
const clientX = e.touches[0].clientX;
const newValue = calculateValue(clientX);
const calculatedValue = calculateValue(clientX);
if (props.range) {
const val = [...rangeValue.value];
val[activeThumbIndex.value] = newValue;
updateValue(val);
// 范围模式:更新当前活动滑块的值
const updatedValues = [...rangeValue.value];
updatedValues[activeThumbIndex.value] = calculatedValue;
updateValue(updatedValues);
} else {
updateValue(newValue);
// 单值模式:直接更新滑块值
updateValue(calculatedValue);
}
}
// 触摸结束事件,触发change事件
// 触摸结束事件:完成拖动,触发最终的change事件
function onTouchEnd() {
if (props.disabled) return;
// 触发change事件表示用户完成了一次完整的拖动操作
if (props.range) {
emit("change", rangeValue.value);
} else {
@@ -376,60 +409,72 @@ function onTouchEnd() {
}
}
// 监听外部v-model的变化保持内部value同步单值模式
// 监听外部传入的modelValue变化保持单值模式内部状态同步
watch(
computed(() => props.modelValue),
(val: number) => {
if (val !== value.value) {
value.value = Math.max(props.min, Math.min(props.max, val));
(newModelValue: number) => {
// 当外部值与内部值不同时,更新内部值并限制在有效范围内
if (newModelValue !== value.value) {
value.value = Math.max(props.min, Math.min(props.max, newModelValue));
}
},
{ immediate: true }
);
// 监听外部v-model:values变化,保持内部rangeValue同步范围模式
// 监听外部传入的values变化保持范围模式内部状态同步
watch(
computed(() => props.values),
(val: number[]) => {
rangeValue.value = val.map((e) => {
return Math.max(props.min, Math.min(props.max, e));
(newValues: number[]) => {
// 将外部传入的数组值映射并限制在有效范围内
rangeValue.value = newValues.map((singleValue) => {
return Math.max(props.min, Math.min(props.max, singleValue));
});
},
{ immediate: true }
);
// 监听max的变化,确保value不会超过max
// 监听最大值变化,确保当前值不会超过新的最大值
watch(
computed(() => props.max),
(val: number) => {
(newMaxValue: number) => {
if (props.range) {
const rangeVal = rangeValue.value;
if (rangeVal[0] > val || rangeVal[1] > val) {
updateValue([Math.min(rangeVal[0], val), Math.min(rangeVal[1], val)]);
// 范围模式:检查并调整两个滑块的值
const currentRangeValues = rangeValue.value;
if (currentRangeValues[0] > newMaxValue || currentRangeValues[1] > newMaxValue) {
updateValue([
Math.min(currentRangeValues[0], newMaxValue),
Math.min(currentRangeValues[1], newMaxValue)
]);
}
} else {
const singleVal = value.value;
if (singleVal > val) {
updateValue(val);
// 单值模式:检查并调整单个滑块的值
const currentSingleValue = value.value;
if (currentSingleValue > newMaxValue) {
updateValue(newMaxValue);
}
}
},
{ immediate: true }
);
// 监听min的变化,确保value不会小于min
// 监听最小值变化,确保当前值不会小于新的最小值
watch(
computed(() => props.min),
(val: number) => {
(newMinValue: number) => {
if (props.range) {
const rangeVal = rangeValue.value;
if (rangeVal[0] < val || rangeVal[1] < val) {
updateValue([Math.max(rangeVal[0], val), Math.max(rangeVal[1], val)]);
// 范围模式:检查并调整两个滑块的值
const currentRangeValues = rangeValue.value;
if (currentRangeValues[0] < newMinValue || currentRangeValues[1] < newMinValue) {
updateValue([
Math.max(currentRangeValues[0], newMinValue),
Math.max(currentRangeValues[1], newMinValue)
]);
}
} else {
const singleVal = value.value;
if (singleVal < val) {
updateValue(val);
// 单值模式:检查并调整单个滑块的值
const currentSingleValue = value.value;
if (currentSingleValue < newMinValue) {
updateValue(newMinValue);
}
}
},