使用Watir检测元素是否被溢出隐藏

时间:2012-07-10 14:02:18

标签: overflow watir watir-webdriver

我想使用Watir来判断是否使用overflow:hidden css属性隐藏了一个元素。我想到的唯一方法就是找出包含div的位置,看看包含的元素是否在其中。像可见的方法?和礼物?即使包含的元素被完全隐藏,也返回true。

有更好的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

一种选择可能是使用document.elementFromPoint(x,y)。这应该告诉你顶部元素在特定坐标处是什么。如果你的元素由于溢出而被隐藏,它将返回一个不同的元素。

以下内容似乎适用于w3schools.com上的示例:

require 'rubygems'
require 'watir-webdriver'
b = Watir::Browser.new :firefox

class Watir::Element
    def hidden_by_overflow?()
        assert_exists
        assert_enabled

        # Add one to the coordinates because, otherwise, if there is no border       
        # between this element and another element, we might get the element right   
        # above or to the left of this one                                           
        top_left_x = @element.location.x + 1
        top_left_y = @element.location.y + 1
        top_test = browser.execute_script("return document.elementFromPoint(#{top_left_x}, #{top_left_y})")

        return top_test != self
    end
end

begin
    b.goto('http://www.w3schools.com/cssref/playit.asp?filename=playcss_overflow&preval=hidden')
    b.div(:id, 'demoDIV').ps.each{ |x| puts x.hidden_by_overflow? }
    #=> The first 9 paragraphs of the 16 paragraphs return true.
ensure
    b.close
end

注意:

  • 我在Firefox中对此进行了测试。不确定它是否与浏览器兼容。
  • 检查仅检查元素的左上角是否未隐藏。部分位于包含div之外的元素仍将返回true。我尝试使用@ element.size.height检查底角,但是webdriver开始在包含div中滚动结果。