日期:2014-05-16 浏览次数:20409 次
?
忘了是在哪里拷贝的,觉得很有用,今天用js做自动补全效果的时候到网上几乎搜了半个小时才搜索到页面元素的坐标获取方式,这种方法不管是元素外面有多少个父容器,他总是获取的是到页面左侧和丁侧的距离:
?
?
这个getElementPos方法的原理也很清楚了——以这个节点为基础向外循环所有节点并计算出他们到其父容器的高度和宽度(貌似是offsetLeft,和offsetTop)?,把所有的left相加就是X坐标,把左右的top相加 就是Y坐标
?
?
具体实现如下:
?
?
function getElementPos(elementId) {
?var ua = navigator.userAgent.toLowerCase();
?var isOpera = (ua.indexOf('opera') != -1);
?var isIE = (ua.indexOf('msie') != -1 && !isOpera); // not opera spoof
?var el = document.getElementById(elementId);
?if(el.parentNode === null || el.style.display == 'none') {
? return false;
?}?????
?var parent = null;
?var pos = [];????
?var box;????
?if(el.getBoundingClientRect)??? //IE
?{????????
? box = el.getBoundingClientRect();
? var scrollTop = Math.max(document.documentElement.scrollTop,
document.body.scrollTop);
? var scrollLeft = Math.max(document.documentElement.scrollLeft,
document.body.scrollLeft);
? return {x:box.left + scrollLeft, y:box.top + scrollTop};
?}else if(document.getBoxObjectFor)??? // gecko???
?{
? box = document.getBoxObjectFor(el);
? var borderLeft = (el.style.borderLeftWidth)?parseInt
(el.style.borderLeftWidth):0;
? var borderTop = (el.style.borderTopWidth)?parseInt(el.style.borderTopWidth):0;
? pos = [box.x - borderLeft, box.y - borderTop];
?} else??? // safari & opera???
?{
? pos = [el.offsetLeft, el.offsetTop];?
? parent = el.offsetParent;????
? if (parent != el) {
?? while (parent) {?
??? pos[0] += parent.offsetLeft;
??? pos[1] += parent.offsetTop;
??? parent = parent.offsetParent;
?? }?
? }??
? if (ua.indexOf('opera') != -1 || ( ua.indexOf('safari') != -1 &&
el.style.position == 'absolute' )) {
?? pos[0] -= document.body.offsetLeft;
?? pos[1] -= document.body.offsetTop;????????
? }???
?}?????????????
?if (el.parentNode) {
??? parent = el.parentNode;
?? } else {
??? parent = null;
?? }
?while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') { //
account for any scrolled ancestors
? pos[0] -= parent.scrollLeft;
? pos[1] -= parent.scrollTop;
? if (parent.parentNode) {
?? parent = parent.parentNode;
? } else {
?? parent = null;
? }
?}
?return {x:pos[0], y:pos[1]};
}
这样获取:
var pos=getElementPos("这里的是元素的id");
距离页面顶层的距离:var height_yuansu=pos.y;
距离页面左侧的距离:var width_yuansu=pos.x;
?