2017-01-27 74 views
1

我一直在试图找到一种方法来确认光标在输入字段内(模拟在该字段内单击)。Selenium确认光标位置

有一种情况,如果某个字段条目未通过验证,则会在网页顶部调用错误消息。

错误消息是一个超链接,当按下时,滚动指向输入字段所在的页面,并将光标放在字段中。

有没有办法确认光标在框中?

由于

回答

2

当光标在文本字段中,这意味着该文本字段处于焦点或是有源元件。水豚不直接提供这种方法。但是,有几个选项。

切换到有源元件

如果下降到底层硒驱动程序,你可以retrive的有源元件:

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获取有关活动元素的一些细节。例如,以下内容返回焦点元素的ID:

active_id = page.evaluate_script("document.activeElement.id") 
expect(active_id).to eq('field_id') 
+0

我尝试了两种解决方案。在评估Javascript时,我预计会发现x但是没有。 – Tom

+0

在点击和期望之间添加2秒钟的睡眠后,它就起作用了。谢谢 – Tom