javascript获得DOM元素X,Y坐标的函数
以下是YUI用的函数:
Js代码
- isSafari = (document.childNodes && !document.all && !navigator.taintEnabled);
- var getXY = function(el) {
- if (document.documentElement.getBoundingClientRect) { // IE
- var box = el.getBoundingClientRect();
- var rootNode = el.ownerDocument;
- return [box.left + getDocumentScrollLeft(rootNode), box.top +
- getDocumentScrollTop(rootNode)];
- } else {
- var pos = [el.offsetLeft, el.offsetTop];
- var parentNode = el.offsetParent;
- // safari: subtract body offsets if el is abs (or any offsetParent), unless body is offsetParent
- var accountForBody = (isSafari &&
- el.style['position'] == 'absolute' &&
- el.offsetParent == el.ownerDocument.body);
- if (parentNode != el) {
- while (parentNode) {
- pos[0] += parentNode.offsetLeft;
- pos[1] += parentNode.offsetTop;
- if (!accountForBody && isSafari &&
- parentNode.style['position'] == 'absolute' ) {
- accountForBody = true;
- }
- parentNode = parentNode.offsetParent;
- }
- }
- if (accountForBody) { //safari doubles in this case
- pos[0] -= el.ownerDocument.body.offsetLeft;
- pos[1] -= el.ownerDocument.body.offsetTop;
- }
- parentNode = el.parentNode;
- // account for any scrolled ancestors
- while ( parentNode.tagName && !/^body|html$/i.test(parentNode.tagName) )
- {
- // work around opera inline/table scrollLeft/Top bug
- if (parentNode.style['display'].search(/^inline|table-row.*$/i)) {
- pos[0] -= parentNode.scrollLeft;
- pos[1] -= parentNode.scrollTop;
- }
- parentNode = parentNode.parentNode;
- }
- return pos;
- }
- }
- getDocumentScrollLeft = function(doc) {
- doc = doc || document;
- return Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);
- },
- getDocumentScrollTop = function(doc) {
- doc = doc || document;
- return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
- }
下面是精简版:
Js代码
- function getX(obj){
- return obj.offsetLeft + (obj.offsetParent ? getX(obj.offsetParent) : obj.x ? obj.x : 0);
- }
- function getY(obj){
- return (obj.offsetParent ? obj.offsetTop + getY(obj.offsetParent) : obj.y ? obj.y : 0);
- }
不过只支持IE和FF