实现逻辑:Slider组件的滑块不支持自定义布局,本方案使用Stack容器,在Slider的上层覆盖一个与滑块大小相同的Row组件,在Row组件中实现自定义布局内容,滑动滑块时,获取滑块位置传递给Row组件的offset,实现Row组件的同步移动。
Slider({ style: SliderStyle.OutSet, value: 0 })
.width(this.slideWidth)
.blockSize({ width: this.blockWidth, height: this.blockHeight })
.blockColor(Color.Transparent)
.blockStyle({
type: SliderBlockType.SHAPE,
shape: new Rect({ width: this.blockWidth, height: this.blockHeight }).radius(5)
}) Row() {
Text('自定义')
.fontSize(10);
}
.width(this.blockWidth)
.height(this.blockHeight)
.borderRadius(5)
.hitTestBehavior(HitTestMode.Transparent)
.backgroundColor(Color.Grey)
.justifyContent(FlexAlign.Center)
.offset({
x: this.tipsOffset
}); Slider({ style: SliderStyle.OutSet, value: 0 })
.width(this.slideWidth)
.blockSize({ width: this.blockWidth, height: this.blockHeight })
.blockColor(Color.Transparent)
.blockStyle({
type: SliderBlockType.SHAPE,
shape: new Rect({ width: this.blockWidth, height: this.blockHeight }).radius(5)
})
.onChange((value: number) => {
this.showTip(value);
}); private showTip(value: number) {
let percent = Number((value / 100).toFixed(2));
this.tipsOffset = this.slideMargin + (this.slideWidth - this.blockWidth - this.slideMargin * 2) * percent;
} 实现效果:

@Entry
@Component
struct SliderExample {
private slideMargin: number = 4;
@State tipsOffset: number = this.slideMargin;
private slideWidth: number = 340;
private blockWidth: number = 60;
private blockHeight: number = 20;
build() {
Column() {
Stack({ alignContent: Alignment.Start }) {
Slider({ style: SliderStyle.OutSet, value: 0 })
.width(this.slideWidth)
.blockSize({ width: this.blockWidth, height: this.blockHeight })
.blockColor(Color.Transparent)
.blockStyle({
type: SliderBlockType.SHAPE,
shape: new Rect({ width: this.blockWidth, height: this.blockHeight }).radius(5)
})
.onChange((value: number) => {
this.showTip(value);
});
Row() {
Text('自定义')
.fontSize(10);
}
.width(this.blockWidth)
.height(this.blockHeight)
.borderRadius(5)
.hitTestBehavior(HitTestMode.Transparent)
.backgroundColor(Color.Grey)
.justifyContent(FlexAlign.Center)
.offset({
x: this.tipsOffset
});
}
.margin({ left: 30, top: 300 });
};
}
private showTip(value: number) {
let percent = Number((value / 100).toFixed(2));
this.tipsOffset = this.slideMargin + (this.slideWidth - this.blockWidth - this.slideMargin * 2) * percent;
}
}