获取元素在浏览器中的绝对位置(从jquery1.8中抠出来)
Posted codeing or artist ?
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取元素在浏览器中的绝对位置(从jquery1.8中抠出来)相关的知识,希望对你有一定的参考价值。
<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 };
以上是关于获取元素在浏览器中的绝对位置(从jquery1.8中抠出来)的主要内容,如果未能解决你的问题,请参考以下文章