问题描述
我真的很惊讶,我无法在Internet上找到使用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 .但是,直接阅读常见问题解答使我认为必须有某种方法可以使用驱动程序本身执行检查.
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测试元素是否聚焦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!