0

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

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

添加:

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

4

2 回答 2

0

我现在已经实现了对在 VimFx中发现可滚动元素的支持。

解决这个问题的关键是使用 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!
}
于 2015-01-26T16:48:51.720 回答
0

您可以使用 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
  }
}
于 2012-11-15T13:41:40.917 回答