【问题标题】:How to find scrollable elements in DOM using XPath?如何使用 XPath 在 DOM 中查找可滚动元素?
【发布时间】:2012-11-15 13:20:54
【问题描述】:

基本上我需要找到页面上所有具有滚动条(垂直或水平)的元素

如何判断一个元素是否有滚动条并且可以滚动?我找到了this code snippet on jsperf。是否可以将代码背后的逻辑捕获到 XPath 表达式中?或者还有其他方法可以检查滚动条吗?

添加:

只是为了解释我想要做什么:我正在开发 VimFx - Firefox 的扩展。基本上它引入了 Vim 风格的无鼠标快捷方式(我知道有 Vimperator 和 Pentadactyl ......)。我想实现的功能之一是允许用户选择使用 j/k 键滚动的容器。这就是为什么我需要发现任何给定随机页面上的所有可滚动元素。

【问题讨论】:

  • XPath 无法访问有关元素如何呈现的信息,因此这是不可能的。

标签: javascript dom xpath scrollbar element


【解决方案1】:

你可以用javscript检查是否溢出了一个div设置为“滚动”

document.getElementById(elementId).style.overflow == "scroll";

我会检查每个艰难的元素。如果你所有的元素都是 divs' 然后使用这个:

var allElements = document.getElementsByTagName("div");
for(index in allElements) {
  var element = allElements[index];
  if (element.style.overflow == "scroll" || element.style.overflowX == "scroll" || element.style.overflowY == "scroll"){
    //do something
  }
}

【讨论】:

  • 我想我必须走 JS 路径。问题是,在我的情况下,任何元素都可能是可滚动的......
  • 这仅适用于可滚动元素的样式内联以使用overflow: scroll。使用window.getComputedStyle() 会更好,但速度很慢。尽管如此,大多数可滚动元素都有overflow: auto,这意味着它们只有在需要时才有滚动条。然后仍然需要以某种方式确定元素是否真的可滚动的。
【解决方案2】:

我现在已经在 VimFx 中实现了support for discovering scrollable elements

解决这个问题的关键是使用Mozilla特定的事件overflowunderflow

概念是:

// The function used for the overflow event:
function(event) {
  // `window` is a reference to the current window.
  var computedStyle = window.getComputedStyle(event.target)
  // `overflow: hidden` can cause overflow, but without a scrollbar, so
  // exclude such elements
  if (computedStyle && computedStyle.getPropertyValue('overflow') == 'hidden') {
    return
  }
  // `scrollableElements` is a reference to a `WeakMap` object for the
  // current window.
  scrollableElements.set(event.target)
}

// The function used for the underflow event:
function(event) {
  scrollableElements.delete(event.target)
}

// Somewhere else in the code we can now get a suitable `scrollableElements`
// object and check if elements are present in it.
if (scrollableElements.has(someElement)) {
  // `someElement` is scrollable!
}

【讨论】:

    猜你喜欢
    • 2014-08-07
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多