1. 程式人生 > >2.10

2.10

attr red 指定 href .get style arguments asc string

來源: 使用Webdriver執行JS小結 http://lijingshou.iteye.com/blog/2018929

1.直接傳入Javascript代碼

可以直接給js傳入javascript代碼:

Java代碼 技術分享
  1. js.executeScript("window.document.getElementById(‘jingshou‘).click()";

2.傳入WebElement執行JS:

Java代碼 技術分享
  1. WebElement element = driver.findElement(By.id("jingshou"));
  2. js.executeScript("arguments[0].click();", element);

又或者:

Java代碼 技術分享
  1. js.executeScript("arguments[0].onclick=function(){alert(‘This is my alert!‘);}", element)

其中auguments[0]就代表element, 甚至我們可以傳入更多的參數,比如

Java代碼 技術分享
  1. WebElement div = driver.findElemnt(By.id("myDiv"));
  2. jse.executeScript("arguments[0].setAttribute(‘style‘, arguments[1])", div, "height: 1000px");

通過執行以上代碼,我們指定的DIV就新增(修改)了 style {height: 1000px}的屬性

ex. 使用JavaScript語句將傳入參數(頁面元素對象)的背景顏色和邊框顏色分別設置為 黃色、紅色

JavascriptExecutor js=(JavascriptExecutor)  driver;
js.executeScript("arguments[0].setAttribute(‘style‘,arguments[1]);", element,"background: yellow; border:2px solid red;");

2.10