鼠標事件

2024-01-22 11:22 更新

在鼠標的單個動作觸發(fā)多個事件時,事件的順序是固定的,鼠標事件默認透傳。

說明
  • 從API Version 8開始支持。后續(xù)版本如有新增內(nèi)容,則采用上角標單獨標記該內(nèi)容的起始版本。
  • 目前僅支持通過外接鼠標觸發(fā)。

事件

名稱

支持冒泡

描述

onHover(event: (isHover?: boolean) => void)

鼠標進入或退出組件時觸發(fā)該回調(diào)。

isHover:表示鼠標是否懸浮在組件上,鼠標進入時為true, 退出時為false。

onMouse(event: (event?: MouseEvent) => void)

當前組件被鼠標按鍵點擊時或者鼠標在組件上懸浮移動時,觸發(fā)該回調(diào),event返回值包含觸發(fā)事件時的時間戳、鼠標按鍵、動作、鼠標位置在整個屏幕上的坐標和相對于當前組件的坐標。

MouseEvent對象說明

名稱

屬性類型

描述

screenX

number

鼠標位置相對于應(yīng)用窗口左上角的x軸坐標。

screenY

number

鼠標位置相對于應(yīng)用窗口左上角的y軸坐標。

x

number

鼠標位置相對于當前組件左上角的x軸坐標。

y

number

鼠標位置相對于當前組件左上角的y軸坐標。

button

MouseButton

鼠標按鍵。

action

MouseAction

鼠標動作。

stopPropagation

() => void

阻塞事件冒泡。

timestamp8+

number

事件時間戳。觸發(fā)事件時距離系統(tǒng)啟動的時間間隔,單位納秒。

target8+

EventTarget

觸發(fā)事件的元素對象顯示區(qū)域。

source8+

SourceType

事件輸入設(shè)備。

示例

  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct MouseEventExample {
  5. @State hoverText: string = 'no hover';
  6. @State mouseText: string = '';
  7. @State action: string = '';
  8. @State mouseBtn: string = '';
  9. @State color: Color = Color.Blue;
  10. build() {
  11. Column({ space: 20 }) {
  12. Button(this.hoverText)
  13. .width(180).height(80)
  14. .backgroundColor(this.color)
  15. .onHover((isHover: boolean) => {
  16. // 通過onHover事件動態(tài)修改按鈕在是否有鼠標懸浮時的文本內(nèi)容與背景顏色
  17. if (isHover) {
  18. this.hoverText = 'hover';
  19. this.color = Color.Pink;
  20. } else {
  21. this.hoverText = 'no hover';
  22. this.color = Color.Blue;
  23. }
  24. })
  25. Button('onMouse')
  26. .width(180).height(80)
  27. .onMouse((event: MouseEvent) => {
  28. switch (event.button) {
  29. case MouseButton.None:
  30. this.mouseBtn = 'None';
  31. break;
  32. case MouseButton.Left:
  33. this.mouseBtn = 'Left';
  34. break;
  35. case MouseButton.Right:
  36. this.mouseBtn = 'Right';
  37. break;
  38. case MouseButton.Back:
  39. this.mouseBtn = 'Back';
  40. break;
  41. case MouseButton.Forward:
  42. this.mouseBtn = 'Forward';
  43. break;
  44. case MouseButton.Middle:
  45. this.mouseBtn = 'Middle';
  46. break;
  47. }
  48. switch (event.action) {
  49. case MouseAction.Hover:
  50. this.action = 'Hover';
  51. break;
  52. case MouseAction.Press:
  53. this.action = 'Press';
  54. break;
  55. case MouseAction.Move:
  56. this.action = 'Move';
  57. break;
  58. case MouseAction.Release:
  59. this.action = 'Release';
  60. break;
  61. }
  62. this.mouseText = 'onMouse:\nButton = ' + this.mouseBtn +
  63. '\nAction = ' + this.action + '\nXY=(' + event.x + ',' + event.y + ')' +
  64. '\nscreenXY=(' + event.screenX + ',' + event.screenY + ')';
  65. })
  66. Text(this.mouseText)
  67. }.padding({ top: 30 }).width('100%')
  68. }
  69. }

示意圖:

鼠標懸浮時改變文本內(nèi)容與背景顏色:

鼠標點擊時:

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號