检查元素是否真正对用户可见 [英] Checking if an element is really visible to the user

查看:67
本文介绍了检查元素是否真正对用户可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查用户是否可以在不滚动的情况下在当前Web浏览器视图中看到一个元素.

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.

建议使用另一个提示来检查元素的位置,但随后我需要获取浏览器可见窗口的尺寸及其 x/y 偏移为 0/0 .

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.

如果有人可以向我指出不需要JavaScript代码的解决方案,我将不胜感激.

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

推荐答案

您如何定义对用户可见"?您打算如何检查? 如果有高度?如果CSS不隐藏它?如果父元素被CSS隐藏了怎么办?

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?

最可靠的方法是使用Selenium内置的.Displayed属性(如果您使用的是C#,则Java具有类似功能),并将其与jQuery的可见"选择器结合使用:

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;

这将解决大多数情况.

如果没有客户端代码,或者在别人发现可以用服务器端语言完成的方式的准备中,这是不可能的,我非常怀疑它的外观,可读性或可靠性.

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具有offset()方法:

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.

这篇关于检查元素是否真正对用户可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆