开发者

How to get an DOM Element [x,y] coordinates relative to the scrollbox?

开发者 https://www.devze.com 2023-01-17 16:38 出处:网络
How to get an DOM Element [x,y] coordinates in javascript? Specifically, the coordinates of a butto开发者_JAVA技巧n inside a scrollbox.

How to get an DOM Element [x,y] coordinates in javascript? Specifically, the coordinates of a butto开发者_JAVA技巧n inside a scrollbox.

I found this offsetLeft attribute:

var elements = scroll.children; // with 12 children
if (!elements.item(2)) {
    print("no element");
}
else if (!elements.item(2).offsetLeft) {
    print("no attribute");
}
else {
    print(elements.item(2).offsetLeft);
}

but it's printing "no attribute"...

By the way, it's for Mozilla environment.


Try something like this:

// Based on code from http://www.quirksmode.org/js/findpos.html
function FindElementDocumentPosition(element) {
  var left = 0;
  var top = 0;
  var lastElement = element;
  if (element.offsetParent) {
    left += element.offsetLeft;
    top += element.offsetTop;
    element = element.offsetParent;
    while (element) {
      left += element.offsetLeft;
      top += element.offsetTop;
      left -= element.scrollLeft;
      top -= element.scrollTop;
      lastElement = element;
      element = element.offsetParent;
    }
  }
  // Adjust for document scroll position
  var agent = navigator.userAgent.toLowerCase();
  if (!PageInStandardsMode() || (agent.indexOf('firefox') == -1)) {
    var leftAdjust = document.body.scrollLeft || document.documentElement.scrollLeft;
    var topAdjust = document.body.scrollTop || document.documentElement.scrollTop;
    left += leftAdjust;
    top += topAdjust;
  }
  return {
    x: left,
    y: top
  };
}
0

精彩评论

暂无评论...
验证码 换一张
取 消