<style> html,body{margin:0;padding:0;} .d1{margin-left:40px;background:red;width:2000px;height:100px;position:relative;} .d2{margin-left:40px;background:blue;width:1000px;height:80px;} </style> <div id="d1" class="d1"> <div id="d2" class="d2"></div> </div>
function getWindow( elem ) { return mylibs.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; }; var mylibs = { isWindow: function( obj ) { return obj != null && obj == obj.window; }, //获取元素在浏览器中的绝对位置 offset:function(elem){ var docElem, win, clientTop, clientLeft, scrollTop, scrollLeft, box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; //黑莓5 ios3(iphoe) 没有getBoundingClientRect if ( typeof elem.getBoundingClientRect !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); clientTop = docElem.clientTop || document.body.clientTop || 0; clientLeft = docElem.clientLeft || document.body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; } }; //调用: document.getElementById('d2').onclick = function(){ alert(mylibs.offset(this).left); };