如何使用C#在selenium中使用JavaScriptExecutor将style属性设置为div

时间:2018-02-02 07:52:10

标签: javascript c# html selenium

我正在尝试使用C#使用JavascriptExecutor设置div元素的样式。 下面是我尝试的代码,但没有任何反应

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;  
IWebElement element = driver.FindElement(By.XPath("//div[contains(@class,'rmSlide')]"));
js.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2])", 
element, "style", 
"visibility: visible;
height: 259px; 
width: 339px;
display: block;
overflow: hidden;
left: -81px;
top: 24px;
z-index: 2; "
);

我要做的就是从display: block

设置display: none

下面是元素的Html

enter image description here

2 个答案:

答案 0 :(得分:1)

当您尝试将属性display: none;更改为display: block;时,您可以使用以下代码块:

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;  
IWebElement element = driver.FindElement(By.XPath("//div[contains(@class,'rmSlide')]"));
var script = "arguments[0].style.display='block';";
js.ExecuteScript(script, element);

答案 1 :(得分:0)

我得到了正确的代码,只是修改了并在元素上添加了鼠标悬停,下面是代码。

var element = driver.FindElement(By.XPath("xpathe here"));
Actions action = new Actions(driver);
action.MoveToElement(element).Build().Perform();  

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;  
IWebElement element1 = driver.FindElement(By.XPath("//div[contains(@class,'rmSlide')]"));
js.ExecuteScript("arguments[0].setAttribute('style', 'visibility: visible; height: 259px; width: 339px; display: block; overflow: hidden; left: -81px; top: 24px; z - index: 2; ')", element1);