【问题标题】:How to check if element is visible in viewport?如何检查元素在视口中是否可见?
【发布时间】:2018-03-06 15:08:19
【问题描述】:

如果我在页面底部,如果某个元素位于页面顶部,我如何检查该元素是否可见。

我需要编写一个测试,在其中向下滚动到页面底部,当我单击 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。

【问题讨论】:

    标签: grails spock geb


    【解决方案1】:

    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;
    }
    

    【讨论】:

    • 谢谢。我做了只需要父母身高的方法。然后它检查元素是否在那个大小,如果它是可见的。这没什么特别的,但如果我想完全按照测试用例所说的那样做,那么我需要使用 sikuli 脚本 (sikuli.org) 之类的东西,并检查链接是否将我滚动到链接的 div。
    猜你喜欢
    • 2014-01-14
    • 2022-08-15
    • 2017-05-23
    • 2017-01-01
    • 2012-04-21
    • 2012-07-08
    • 1970-01-01
    • 2013-11-09
    相关资源
    最近更新 更多