问题描述
我真的很惊讶我在互联网上找不到使用 Selenium Webdriver 测试元素焦点的参考资料.
I'm really surprised I can't find references on the internet to testing for element focus using Selenium Webdriver.
我想检查何时尝试提交表单而遗漏了必填字段,焦点移至空字段.但我看不到任何使用 WebDriver API 的方法.
I'm wanting to check when when a form submission is attempted with a mandatory field missed, focus is moved to the empty field. But I cannot see any way to do this using the WebDriver API.
我将能够使用 JavascriptExecutor.但是阅读 FAQ 让我觉得一定有某种方法可以使用驱动程序本身来执行检查.
I will be able to find the focused element using a JavascriptExecutor. But reading the FAQ makes me think there must be some way to perform the check using the driver itself.
感谢您的帮助.
推荐答案
driver.switchTo().activeElement()
将返回当前聚焦的WebElement
.WebElement
已经很好地定义了相等性,因此您可以调用 element.equals(driver.switchTo().activeElement())
.
driver.switchTo().activeElement()
will return the currently focused WebElement
. Equality is well defined for WebElement
, so you can call element.equals(driver.switchTo().activeElement())
.
调用有点误导性的名为driver.switchTo().activeElement()
实际上并没有切换焦点,driver.findElement()
也没有,所以你没有需要在 switchTo().defaultContent()
之后;事实上,这样做可能会模糊当前元素.
Calling the slightly misleading named driver.switchTo().activeElement()
does not in fact switch focus, neither does driver.findElement()
, so you do not need to switchTo().defaultContent()
after; in fact, doing so would probably blur the current element.
这篇关于使用 Selenium Webdriver 测试元素是否聚焦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!