HarmonyOS鸿蒙Next中鼠标悬浮时如何设置鼠标指针样式

HarmonyOS鸿蒙Next中鼠标悬浮时如何设置鼠标指针样式

想要实现鼠标悬浮时,实现设置鼠标指针样式为HAND_POINTING,按照 https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-pointer#pointersetpointerstyle-1 设置不生效。

import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';
import { pointer } from '@kit.InputKit';

@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize($r('app.float.page_text_font_size'))
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          this.message = 'Welcome';
        })
        .onHover((isHover) => {
          if (isHover) {
            window.getLastWindow(getContext(), (error: BusinessError, win: window.Window) => {
              if (error.code) {
                console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
                return;
              }
              let windowId = win.getWindowProperties().id;
              if (windowId < 0) {
                console.log(`Invalid windowId`);
                return;
              }
              try {
                pointer.setPointerStyleSync(windowId, pointer.PointerStyle.HAND_POINTING);
                console.log(`Set pointer style success`);
              } catch (error) {
                console.error(`getPointerSize failed, error: ${JSON.stringify(error, ['code', 'message'])}`);
              }
            });
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}

更多关于HarmonyOS鸿蒙Next中鼠标悬浮时如何设置鼠标指针样式的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS鸿蒙Next中,可以通过PointerStyle类来设置鼠标悬浮时的指针样式。使用setPointerStyle方法,传入所需的样式常量,如PointerStyle.DEFAULTPointerStyle.HAND等,即可改变鼠标指针的外观。具体样式常量可在官方文档中查阅。

更多关于HarmonyOS鸿蒙Next中鼠标悬浮时如何设置鼠标指针样式的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中设置鼠标指针样式,你的代码基本正确但可以简化。推荐使用ArkUI的通用属性pointerStyle直接设置,这是更简洁的方式:

Text(this.message)
  .id('HelloWorld')
  .pointerStyle(PointerStyle.Hand) // 直接设置指针样式
  .onHover((isHover) => {
    if (isHover) {
      this.message = 'Hovered';
    }
  })

关键点说明:

  1. 使用pointerStyle属性比调用API更高效
  2. 可用样式包括:DefaultHandWaitHelp
  3. 确保在正确的组件上设置该属性

如果仍需要API方式,请检查:

  1. windowId是否正确获取
  2. 是否在正确的生命周期设置
  3. 设备是否支持指针设备

建议优先使用ArkUI属性方式,API方式更适合复杂场景。

回到顶部