<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>
1 function getWindow( elem ) { 2 return mylibs.isWindow( elem ) ? 3 elem : 4 elem.nodeType === 9 ? 5 elem.defaultView || elem.parentWindow : 6 false; 7 }; 8 9 var mylibs = { 10 isWindow: function( obj ) { 11 return obj != null && obj == obj.window; 12 }, 13 //获取元素在浏览器中的绝对位置 14 offset:function(elem){ 15 var docElem, win, clientTop, clientLeft, scrollTop, scrollLeft, 16 box = { top: 0, left: 0 }, 17 doc = elem && elem.ownerDocument; 18 19 docElem = doc.documentElement; 20 //黑莓5 ios3(iphoe) 没有getBoundingClientRect 21 if ( typeof elem.getBoundingClientRect !== "undefined" ) { 22 box = elem.getBoundingClientRect(); 23 } 24 win = getWindow( doc ); 25 26 clientTop = docElem.clientTop || document.body.clientTop || 0; 27 clientLeft = docElem.clientLeft || document.body.clientLeft || 0; 28 scrollTop = win.pageYOffset || docElem.scrollTop; 29 scrollLeft = win.pageXOffset || docElem.scrollLeft; 30 return { 31 top: box.top + scrollTop - clientTop, 32 left: box.left + scrollLeft - clientLeft 33 }; 34 } 35 }; 36 37 document.getElementById(‘d2‘).onclick = function(){ 38 alert(mylibs.offset(this).left); 39 };
时间: 2024-12-17 15:21:15