2013-10-10 41 views
0

我需要使用JavaScript做mouseover功能,我試過下面的代碼沒有得到任何錯誤,但沒有發生鼠標懸停功能。如何在使用JavaScript的硒webdriver做mouseover功能

 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); 
+0

您可以使用動作類來執行鼠標相關的活動。 – Vinay

+0

已經我使用的動作類它不適用於所有瀏覽器和所有應用程序,這就是我要通過javascript – Raghu

+0

String javaScript =「var evObj = document.createEvent('MouseEvents');」 +「evObj.initMouseEvent(\」mouseover \「,true,false,window,0,0,0,0,0,false,false,false,0,null);」 +「arguments [0] .dispatchEvent(evObj);」; ((JavascriptExecutor)Driver.driver).executeScript(javaScript,element);這應該工作。試一試。 – Vinay

回答

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

希望這將有助於

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 
    } 
}