AutoJs相关学习
一、控件点击、模拟点击
如果一个控件的 clickable=false,但它的父级控件是 clickable=true,我们可以通过 向上查找父级控件 的方式找到可点击的父级,然后执行点击操作。以下是几种实现方法:
方法 1:使用 parent() 查找可点击的父级
let submitText = text("提交").findOne(); // 找到目标控件
let clickableParent = submitText.parent().findOne(clickable(true)); // 查找可点击的父级if (clickableParent) {clickableParent.click(); // 点击父级
} else {console.log("未找到可点击的父级");
}
方法 2:使用 bounds() 计算中心点并点击
如果父级也无法点击,可以 直接计算控件位置并模拟点击:
let submitText = text("提交").findOne();
let bounds = submitText.bounds();
click(bounds.centerX(), bounds.centerY()); // 点击中心点
方法 3:使用 untilFind() 结合 parent()
let submitText = text("提交").findOne();
let clickableParent = submitText.parent().untilFind(clickable(true), 5000); // 5秒内查找if (clickableParent.length > 0) {clickableParent[0].click();
} else {console.log("未找到可点击的父级");
}
二、点击某个控件的左侧偏移位置
在 Auto.js 中,如果你需要点击某个控件的 左侧偏移位置(即控件左边一定距离的位置),可以使用 bounds()
获取控件坐标后计算偏移位置,然后用click()
点击。以下是几种实现方法:
方法 1:基于 bounds() 计算偏移点击
// 找到目标控件(例如一个按钮)
let target = text("确定").findOne();
if (target) {// 获取控件的位置和大小let bounds = target.bounds();// 计算左侧偏移 50px 的坐标(x 减小,y 保持中心)let offsetX = bounds.left - 50; // 向左偏移 50 像素let offsetY = bounds.centerY(); // Y 轴居中// 检查是否超出屏幕边界(可选)if (offsetX < 0) offsetX = 0; // 防止点击负坐标// 执行点击click(offsetX, offsetY);console.log("已点击坐标:", offsetX, offsetY);
} else {console.log("未找到目标控件");
}
方法 2:使用 click(offsetX, offsetY)
直接偏移
如果控件本身可点击,但你想点击它的左侧区域,可以结合 click(offsetX, offsetY)
:
let target = id("btn_submit").findOne();
if (target) {// 点击控件左侧 30px 的位置(相对控件自身坐标)target.click( -30, 0 ); // X 向左 30px,Y 不变
}
总结
- 优先用 bounds() + click(x,y):最灵活,适用于所有情况。
- 控件可点击时用 target.click(offsetX, offsetY):代码更简洁。
三、多个相同控件时获取最后一个控件
var arrAll = text("头像").find();if (arrAll.nonEmpty()) {target= arrAll.get(arrAll.size() - 1);} // 获取元素位置// var lastIconBounds = arrIcons.get(arrIcons.size() - 1).bounds();// press(lastIconBounds.left - 200, lastIconBounds.top + 50, 300);
解释:
find()
方法会返回所有匹配的控件集合(类似数组)
nonEmpty()
是判断集合是否非空的方法(至少有一个元素)
size()
获取集合中元素的数量
get(index)
通过索引获取集合中的元素,这里用size()-1
获取最后一个元素
四、 findOne() 和 findOnce()
在 Auto.js 中,findOne() 和 findOnce() 都是用于查找 UI 控件的方法,但它们的工作方式有重要区别:
1. findOne()
行为特点:
会持续查找控件,直到找到匹配项或超时(默认 10 秒)
如果找不到控件,会抛出异常 UiObjectNotFoundException
- 典型用法:
let button = text("确定").findOne(); // 默认等待最多 10 秒
button.click();
- 适用场景:
需要确保控件一定存在时才继续执行
需要操作找到的控件(如点击、输入等)
2. findOnce()
- 行为特点:
立即查找一次,如果没找到就返回 null
不会等待,不会抛异常
- 典型用法:
let button = text("确定").findOnce();
if (button) {button.click();
} else {console.log("没找到按钮");
}
- 适用场景:
只需要检查控件是否存在,不关心等待
在循环中快速检查控件状态
4. 代码示例对比
// 使用 findOne()(会等待)
try {let btn = text("提交").findOne(5000); // 最多等 5 秒btn.click();
} catch (e) {console.log("5秒内没找到提交按钮");
}// 使用 findOnce()(立即返回)
let btn = text("提交").findOnce();
if (btn) {btn.click();
} else {console.log("当前没找到提交按钮");
}