目录

PC应用内组件如何实现悬浮样式Hover效果

问题现象

PC应用如何实现鼠标悬停在组件上时,组件UI效果变更?

效果预览

背景知识

解决方案

例如按钮的默认状态、按下状态、禁用状态可以将@Styles与stateStyles组合使用来实现对应效果,悬浮状态还需要结合onHover事件来实现。

// 定义在全局的Button样式
@Styles
function globalButtonStyle() {
  .width(160)
  .height(80)
  .borderRadius(16);
}

@Entry
@Component
struct CustomerButton {
  @State isHover: boolean = false;

  // 定义在组件内的@Styles封装的样式
  // Disable
  @Styles
  disabledStyle(){
    .backgroundColor('#A8B8F7');
  }

  // normal
  @Styles
  normalStyle() {
    .backgroundColor('#0A59F7');
  }

  // pressed
  @Styles
  pressedStyle() {
    .backgroundColor('#0950DE');
  }

  // hover
  @Styles
  hoverStyle() {
    .backgroundColor(this.isHover ? '#0954EA' : '#0A59F7');
  }

  build() {
    Column() {
      Row() {
        Text('Default')
          .width(120)
          .fontSize(30);
        Button('默认状态', { type: ButtonType.Normal, stateEffect: false })
          .globalButtonStyle()
          .fontSize(30)
          .stateStyles({
            normal: this.normalStyle
          });
      }
      .margin({
        bottom: 20
      });

      Row() {
        Text('Pressed')
          .width(120)
          .fontSize(30);
        Button('按下状态', { type: ButtonType.Normal, stateEffect: false })
          .globalButtonStyle()
          .fontSize(30)
          .stateStyles({
            normal: this.normalStyle,
            pressed: this.pressedStyle,
          });
      }
      .margin({
        bottom: 20
      });

      Row() {
        Text('Hover')
          .width(120)
          .fontSize(30);
        Button('悬浮状态', { type: ButtonType.Normal, stateEffect: false })
          .globalButtonStyle()
          .fontSize(30)
          .onHover((isHover: boolean) => {
            console.info(`${isHover}`);
            this.isHover = !this.isHover;
          })
          .stateStyles({
            normal: this.hoverStyle
          });
      }
      .margin({
        bottom: 20
      });

      Row() {
        Text('Disable')
          .width(120)
          .fontSize(30);
        Button('禁用状态', { type: ButtonType.Normal, stateEffect: false })
          .globalButtonStyle()
          .fontSize(30)
          .enabled(false)
          .stateStyles({
            disabled: this.disabledStyle
          });
      }
      .margin({
        bottom: 20
      });
    }
    .padding({ top: 20 })
    .width('100%')
    .justifyContent(FlexAlign.Center);
  }
}