0

我正在尝试检查以确保在开始使用以下功能之前可以看到一个项目

isVisible: function (node, doc, x, y) {
    var el = doc.elementFromPoint(x, y);
    if (node === el) return true;
    else return false;
},

xy是所选节点的位置,由下式计算

findPos: function (node) {
    var pos = new Object();
    pos.left = pos.top = 0;
    if (node.offsetParent) {
        do {
            pos.left += node.offsetLeft;
            pos.top += node.offsetTop;

        } while (node = node.offsetParent);
    }
    return pos;
}

一切正常。但是,当我向下滚动页面时,该isVisible函数不再返回正确的值。这是由于位置已更改但查找位置函数未返回正确值引起的。

有没有一种方法可以获取元素的位置,比如 的反面elementFromPoint?或者有人有其他方法吗?

4

3 回答 3

1

I just wrote an isVisible() method that uses the elementFromPoint() method and should work in IE9+ to detect if an element is visible.

var isVisible = function(elem) {
  var w = window, d = document, height, rects, on_top;
  if(!elem || (elem && elem.nodeType !== 1) || !elem.getClientRects || !d.elementFromPoint || !d.querySelector || !elem.contains) {
    return false;
  }
  if (elem.offsetWidth === 0 || elem.offsetHeight === 0) {
    return false;
  }
  height = w.innerHeight ? w.innerHeight: d.documentElement.clientHeight;
  rects = elem.getClientRects();
  on_top = function(r, elem) {
    var x = (r.left + r.right)/2,
      y = (r.top + r.bottom)/2,
      elemFromPoint = d.elementFromPoint(x, y);
      return (elemFromPoint === elem || elem.contains(elemFromPoint));
  };
  for (var i = 0, l = rects.length; i < l; i++) {
    var r = rects[i],
      in_viewport = r.top > 0 ? r.top <= height : (r.bottom > 0 && r.bottom <= height);
    if (in_viewport && on_top(r, elem)) {
      return true;
    }
  }
  return false;
};

You would call it like this: isVisible(document.getElementById('at-follow'));

Also, here is the gist of it.

于 2013-04-04T22:12:27.393 回答
1

我能够通过添加window.scrollX和输入参数window.scrollY来解决这个问题doc.elementFromPoint()xy

    isVisible: function (node, doc, x, y) 
     {
      var el = doc.elementFromPoint(x-window.scrollX, y-window.scrollY);
        if (node === el) return true;
          else return false;
     },

这似乎工作正常

于 2012-06-25T19:59:02.323 回答
0

这个库应该是你要找的:https ://github.com/cpatik/within-viewport/blob/master/withinViewport.js

于 2012-06-24T03:51:01.843 回答