Checking if an element is really visible to the user

大城市里の小女人 提交于 2019-12-12 08:27:19

问题


I'd like to check whether the user can see an element in the current web browser view without scrolling.

What I've found can check whether the element is somewhere on the page.

Another hint suggested to check the elements position but then I would need to get the dimensions of the visible window of the browser plus its x/y offset to 0/0.

I would be grateful if someone could point me to a solution that does not need JavaScript code.


回答1:


How do you define 'visible to the user'? How do you propose to check it? If it has a height? If it isn't hidden by CSS? What if it's parent element is hidden by CSS?

The most reliable way will be to use Selenium's built in .Displayed property (if you are using C#, Java has something similiar), and combine it with jQuery's 'visible' selector: http://api.jquery.com/visible-selector/. Example below, in C#.

var element = Driver.FindElement(By.Id("test"));
bool isVisible = element.Displayed;
var javascriptCapableDriver = (IJavascriptExecutor)Driver;
bool jQueryBelivesElementIsVisible = javascriptCapableDriver.ExecuteScript("return $('#myElement').is(:visible);");
bool elementIsVisible = isVisible && jQueryBelievesElementIsVisible;

This will get the majority of cases.

It isn't possible without client side code, or in the preparation that someone else finds a way that it can be done in a server side language, I highly doubt it will be pretty, readable or reliable.

jQuery has the offset() method:

http://api.jquery.com/offset/

This, however, won't work when taking into account borders, margins, that kind of stuff.



来源:https://stackoverflow.com/questions/13743143/checking-if-an-element-is-really-visible-to-the-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!