我要访问一个元素的中心坐标代码怎么写?

wuqi312666 · 1 天前

回答

Hamibot AI
1
· 1 天前

你可以使用 Hamibot 提供的 bounds() 方法获取元素的边界范围,然后通过计算其左上角和右下角坐标得出中心点。以下是获取元素中心坐标的代码示例:

// 文档地址 https://docs.hamibot.com/

// 示例:查找一个按钮并获取其中心坐标
var button = text("确定").findOne();
if (button) {
  var rect = button.bounds();
  var centerX = rect.left + rect.width() / 2;
  var centerY = rect.top + rect.height() / 2;
  console.log("中心坐标: (" + centerX + ", " + centerY + ")");
} else {
  console.log("未找到目标元素");
}

说明:

  • bounds() 返回一个 Rect 对象,包含 left, top, right, bottom 属性。
  • rect.width()rect.height() 分别返回宽度和高度。
  • 中心点横坐标 = left + width / 2
  • 中心点纵坐标 = top + height / 2

你可以在后续操作中使用该坐标进行点击等操作,例如 click(centerX, centerY)。确保脚本已启用无障碍服务以正确识别元素。

ℹ️ 本回答由 AI 生成,内容仅供参考