我有一个test.html页面,这里是代码。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
</head>
<body>
<span id="test" onMouseover="alert('1')">this is new one</span>
</body>
</html>
我想使用Selenium JavascriptExecutor在测试页面中模拟跨越事件的鼠标,所以我写了这样的代码:
@Test
public void testJSExecutor(){
System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
webDriver = new FirefoxDriver();
webDriver.get("file:\\\\C:/test.html");
String script = "function test(){var t=document.getElementById('test');"
+ "if( document.createEvent ) {"
+ "var evObj = document.createEvent('MouseEvents');"
+ "evObj.initEvent( 'mouseover', true, false );"
+ "elem.dispatchEvent(evObj);"
+"} else if( document.createEventObject ) {"
+ "elem.fireEvent('onmouseover');"
+"}} window.onload=test;";
jsExecutor = (JavascriptExecutor) webDriver;
jsExecutor.executeScript(script);
}
但运行此代码后,没有提示提示。
鼠标悬停事件如何有效,以便提示警报?
答案 0 :(得分:3)
您可以使用以下代码模拟鼠标悬停操作..
Actions actions = new Actions(driver);
WebElement menuHoverLink = driver.findElement(By.id("test"));
actions.moveToElement(menuHoverLink);
actions.perform();