如何使用javascript在selenium webdriver中执行鼠标悬停功能

时间:2013-10-10 06:23:36

标签: java frameworks selenium-webdriver

我需要使用JavaScript执行鼠标悬停功能,我已经尝试了下面的代码我没有收到任何错误但没有发生鼠标悬停功能。

      WebElement Mainmenu=_driver.findElement(By.xpath(locatorvalue[0]));
    String strJavaScript = "var element = arguments[0];"
            + "var mouseEventObj = document.createEvent('MouseEvents');"
            + "mouseEventObj.initEvent( 'mouseover', true, true );"
            + "element.dispatchEvent(mouseEventObj);";
     JavascriptExecutor js =  (JavascriptExecutor) _driver;
     js.executeScript(strJavaScript, Mainmenu);

2 个答案:

答案 0 :(得分:1)

((JavascriptExecutor)driver).executeScript("$('element_selector').hover();");

希望这会有所帮助

答案 1 :(得分:1)

public void click(WebElement a,WebElement b)
{
    try 
     {
         String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover',true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
         ((JavascriptExecutor) driver).executeScript(mouseOverScript,a);
         Thread.sleep(1000);
         ((JavascriptExecutor) driver).executeScript(mouseOverScript,b);
         Thread.sleep(1000);
         ((JavascriptExecutor)driver).executeScript("arguments[0].click();",b);


    } catch (Exception e) {
        // TODO: handle exception
    }
}