可以禁用Slider原本的交互逻辑,通过其他事件修改Slider的进度值value,让滑块直接跳转到进度值对应的位置,从而不显示动画,具体步骤如下:
Row() { Slider({ value: this.value }) .backgroundColor('#f1f3f5') .enabled(false); }
.onAreaChange((oldValue: Area, newValue: Area) => { // 计算得到滑动条的长度(18是滑动条的左右边距) this.sliderLength = (newValue.width as number) - 18; })
.onTouch((e) => { // 按下时触发 if (e.type === TouchType.Down) { // 通过触摸位置和滑动条长度计算占比,得到滑动条的值(9是滑动条的左边距) this.value = (e.touches[0].x - 9) / this.sliderLength * 100; console.info((e.touches[0].x - 9).toString()); } // 拖动触发 if (e.type === TouchType.Move) { this.value = (e.touches[0].x - 9) / this.sliderLength * 100; console.info((e.touches[0].x - 9).toString()); } });
完整代码如下:
@Entry @Component struct SliderExample { @State value: number = 10; // 滑动条的值 sliderLength: number = 0; // 滑动条的长度 build() { Column() { Row() { Slider({ value: this.value }) .backgroundColor('#f1f3f5') .enabled(false); } .onAreaChange((oldValue: Area, newValue: Area) => { // 计算得到滑动条的长度(18是滑动条的左右边距) this.sliderLength = (newValue.width as number) - 18; }) .onTouch((e) => { // 按下时触发 if (e.type === TouchType.Down) { // 通过触摸位置和滑动条长度计算占比,得到滑动条的值(9是滑动条的左边距) this.value = (e.touches[0].x - 9) / this.sliderLength * 100; console.info((e.touches[0].x - 9).toString()); } // 拖动触发 if (e.type === TouchType.Move) { this.value = (e.touches[0].x - 9) / this.sliderLength * 100; console.info((e.touches[0].x - 9).toString()); } }); }; } }