如果我在页面底部,我如何检查某个元素是否可见,如果该元素位于页面顶部。
我需要编写一个测试,在其中向下滚动到页面底部,当我单击 div 时,它会将我移回页面顶部。下一步是检查我是否在那个位置。
我的想法是我只需要检查该元素是否可见,但事实证明这并不容易。有什么建议么?
.isDisplayed() 和 .isFocused() 不是我需要的。
编辑:
我有一个想法,我需要两种方法。
第一个是获取元素的 y 坐标(我们只需要 y),但问题是 getY() 返回相对于您当前位置的数字,所以我需要一些可以将我移动到该元素然后获取 y 坐标的东西。所以我的方法看起来像这样:
int getYCoordinat() {
// first move to the element
interact {
moveToElement(element)
}
// get y coord
return element.getY()
}
第二种方法看起来像这样:
boolean isScrolledToElement(int yCoordinateOfElement) {
int y = element.getY()
return y == yCoordinateOfElement
}
}
所以首先我会调用 getYCoordinat(),将整数存储到 yCoordinateOfElement 中。
然后我会单击将我移动到元素的 div 并调用 isScrolledToElement(yCoordinateOfElement)。
但它不起作用,因为 moveToElement 只有在元素不可见时才会将您移动到该元素。因此,如果我们停留在原地,因为 moveToElement() 没有移动我们,因为元素已经可见,我们会得到错误的 Y 坐标,这与我们点击 div 时得到的坐标不同,将我们移动到元素。
最佳答案
Here is the only solution I could find.基本上,您需要查看元素右下角的像素坐标是否在窗口内。
取自链接:
private boolean isWebElementVisible(WebElement w) {
Dimension weD = w.getSize();
Point weP = w.getLocation();
Dimension d = driver.manage().window().getSize();
int x = d.getWidth();
int y = d.getHeight();
int x2 = weD.getWidth() + weP.getX();
int y2 = weD.getHeight() + weP.getY();
return x2 <= x && y2 <= y;
}
关于grails - 如何检查元素在视口(viewport)中是否可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49134007/