2008-04-30
javascript获得DOM元素X,Y坐标的函数
以下是YUI用的函数:
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;
}
}
/**
* Returns the left scroll value of the document
* @method getDocumentScrollLeft
* @param {HTMLDocument} document (optional) The document to get the scroll value of
* @return {Int} The amount that the document is scrolled to the left
*/
getDocumentScrollLeft = function(doc) {
doc = doc || document;
return Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);
},
/**
* Returns the top scroll value of the document
* @method getDocumentScrollTop
* @param {HTMLDocument} document (optional) The document to get the scroll value of
* @return {Int} The amount that the document is scrolled to the top
*/
getDocumentScrollTop = function(doc) {
doc = doc || document;
return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
}
下面是精简版:
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
发表评论
- 浏览: 12159 次

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
POI拷贝Sheet包括每个单 ...
你好,你写的这个方法正式我说需要的,不过我有2个问题:1、该方法能实现两个不同的 ...
-- by jackini -
自己写OpenCms自定义结构 ...
老兄,这是按页面关键字进行搜索,你知道怎么按网页创建的时间进行搜索吗.急啊!!! ...
-- by zhouxiao315 -
opencms7.0.x plugin for ...
太好了,有更新了
-- by cai555 -
opencms7.0.x plugin for ...
我的环境:Myeclipse6.0(eclipse3.3.1)/openCMS7 ...
-- by foolpcman -
谁能告诉我为什么parseInt ...
居然被评为入门帖,不过还是感谢解答的各位
-- by cai555






评论排行榜