Selenium 确认光标位置
Selenium confirm position of cursor
我一直在努力寻找一种方法来确认光标在输入字段内(以模拟在该字段内单击)。
有一种情况,如果字段条目验证失败,则会在网页顶部调用错误消息。
错误消息是一个超链接,按下该超链接会滚动到该输入字段所在的页面,并将光标置于该字段内。
有没有办法确认光标在框中?
谢谢
当光标位于文本字段中时,这意味着文本字段处于焦点状态或者是活动元素。 Capybara 没有直接为此提供方法。但是,有几个选项。
切换到活动元素
如果你下拉到底层的 Selenium 驱动程序,你可以检索活动元素:
page.driver.browser.switch_to.active_element
=> #<Selenium::WebDriver::Element:0x34409cfc id="0.6429182184051125-3">
使用活动元素,您可以检查它是否是您期望的元素:
# Use Capybara to find the element you expect to be in focus
expected_element = page.find("#field_id")
# Get the element that is actually in focus
active_element = page.driver.browser.switch_to.active_element
# Check that the two elements are the same
# Note that you need to call `native` so that you are comparing Selenium elements
expect(active_element).to eq(expected_element)
使用evaluate_script
另一种方法是使用 JavaScript 获取有关活动元素的一些详细信息。例如下面returns焦点元素的id:
active_id = page.evaluate_script("document.activeElement.id")
expect(active_id).to eq('field_id')
我一直在努力寻找一种方法来确认光标在输入字段内(以模拟在该字段内单击)。
有一种情况,如果字段条目验证失败,则会在网页顶部调用错误消息。
错误消息是一个超链接,按下该超链接会滚动到该输入字段所在的页面,并将光标置于该字段内。
有没有办法确认光标在框中?
谢谢
当光标位于文本字段中时,这意味着文本字段处于焦点状态或者是活动元素。 Capybara 没有直接为此提供方法。但是,有几个选项。
切换到活动元素
如果你下拉到底层的 Selenium 驱动程序,你可以检索活动元素:
page.driver.browser.switch_to.active_element
=> #<Selenium::WebDriver::Element:0x34409cfc id="0.6429182184051125-3">
使用活动元素,您可以检查它是否是您期望的元素:
# Use Capybara to find the element you expect to be in focus
expected_element = page.find("#field_id")
# Get the element that is actually in focus
active_element = page.driver.browser.switch_to.active_element
# Check that the two elements are the same
# Note that you need to call `native` so that you are comparing Selenium elements
expect(active_element).to eq(expected_element)
使用evaluate_script
另一种方法是使用 JavaScript 获取有关活动元素的一些详细信息。例如下面returns焦点元素的id:
active_id = page.evaluate_script("document.activeElement.id")
expect(active_id).to eq('field_id')