使用TextInput组件时,设置提示文字placeholder,当TextInput组件获取焦点时,placeholder提示文字上移到组件左上角,placeholder提示文字缩小,一半在组件外,一半在组件内,如何实现?
@Entry
@Component
struct CustomInputText {
build() {
Column() {
Blank().height(50);
InputComponent({ placeholder: '姓名', inputId: '1', originWeight: 40 });
Blank().height(25);
InputComponent({ placeholder: '电话', inputId: '2', originWeight: 40 });
Blank().height(25);
InputComponent({ placeholder: '户籍', inputId: '3', originWeight: 40 });
Blank().height(25);
InputComponent({ placeholder: '家庭住址', inputId: '4', originWeight: 70 });
}
.height('100%')
.width('100%');
}
}
@Component
struct InputComponent {
text: string = '';
inputId: string | undefined = undefined;
controller: TextInputController = new TextInputController();
placeholder: string = '';
@State textFontSize: number = 20;
@State textHeight: number = 40;
originWeight: number = 0;
@State textWeight: number = 40;
@State textMarginTop: number = 10;
@State textOpacity: number = 0.5;
textBorderWidth: number = 2;
textRadius: number = 10;
// 提示文字缩小时组件配置位标
textMin() {
this.textFontSize = 12;
this.textMarginTop = 0;
this.textOpacity = 1;
this.textHeight = 20;
this.textWeight = 35;
try {
this.getUIContext().getFocusController().requestFocus(this.inputId);
} catch (error) {
// Implement error handling.
}
}
// 提示文字处于初始状态时配置位标
textMax() {
if (this.text !== '') {
return;
}
this.textFontSize = 20;
this.textMarginTop = 10;
this.textOpacity = 0.5;
this.textHeight = 40;
this.textWeight = this.originWeight;
}
build() {
Stack({ alignContent: Alignment.TopStart }) {
TextInput({})
.id(this.inputId)
.fontSize(20)
.width(300)
.height(40)
.margin({ top: 10 })
.opacity(0.5)
.backgroundColor(Color.White)
.defaultFocus(false)
.border({
width: this.textBorderWidth,
color: Color.Black,
radius: this.textRadius,
style: BorderStyle.Solid
})
.onFocus(() => {
this.textMin();
})
.onBlur(() => {
this.textMax();
})
.onChange((value: string) => {
this.text = value;
});
Column() {
Text(this.placeholder)
.fontSize(this.textFontSize * 0.8)
.width(this.originWeight !== 0 ? this.originWeight : this.textWeight)
.height(this.textHeight - this.textBorderWidth * 2)
.opacity(this.textOpacity)
.borderRadius(10)
.textAlign(TextAlign.Center)
.focusable(false)
.renderFit(RenderFit.CENTER)
.animation({
duration: 1000,
curve: Curve.Ease,
iterations: 1,
playMode: PlayMode.Normal
})
.onClick(() => {
this.textMin();
})
.onBlur(() => {
this.textMax();
});
}
.borderRadius(10)
.margin({
top: this.textMarginTop + this.textBorderWidth,
left: this.textBorderWidth * 3,
bottom: this.textBorderWidth
})
.backgroundColor(Color.White)
.animation({
duration: 1000,
curve: Curve.Ease,
iterations: 1,
playMode: PlayMode.Normal
});
};
}
}