- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" lang="gb2312">
- <head>
- <head>
- <title> 代码实例:获取任意Html元素与body之间的偏移距离 offsetTop、offsetLeft </title>
- <meta http-equiv="content-type" content="text/html; charset=gb2312" />
- <meta content="枫岩,CNLei.y.l@gmail.com">
- <style type="text/css" media="all">
- body,p {margin:0;padding:0;font-size:12px;}
- body {float:left;width:100%;}
- ul,ul li {margin:0;padding:0;list-style:none;padding:0;}
- ul li input {border:1px solid #ccc;}
- #Bd {
- background:#FFE8D9;
- float:left;
- padding:20px;
- border:10px solid #f90;/*该值在IE下还是取不到*/
- width:100%;
- }
- #BS {
- padding:20px;
- float:left;
- background:#58CB64;
- }
- #BS ul {border:20px solid #DDF1D8;}
- #BM {
- margin-top:100px;
- float:right;
- width:300px;
- background:#fff;
- }
- </style>
- <script type="text/javascript">
- var w3c=(document.getElementById)? true:false;
- var agt=navigator.userAgent.toLowerCase();
- var ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1) && (agt.indexOf("omniweb") == -1));
- var ie5=(w3c && ie)? true : false;
- var ns6=(w3c && (navigator.appName=="Netscape"))? true: false;
- var op8=(navigator.userAgent.toLowerCase().indexOf("opera")==-1)? false:true;
- function Obj(o){
- return document.getElementById(o)?document.getElementById(o):o;
- }
- function GetXYWH(o){
- var nLt=0;
- var nTp=0;
- var ooffsetParent = o;
- while (offsetParent!=null && offsetParent!=document.body) {
- nLt+=offsetParent.offsetLeft;
- nTp+=offsetParent.offsetTop;
- if(!ns6){
- parseInt(offsetParent.currentStyle.borderLeftWidth)>0?nLt+=parseInt(offsetParent.currentStyle.borderLeftWidth):"";
- parseInt(offsetParent.currentStyle.borderTopWidth)>0?nTp+=parseInt(offsetParent.currentStyle.borderTopWidth):"";
- }
- offsetParentoffsetParent=offsetParent.offsetParent;
- //alert(offsetParent.tagName);
- }
- alert("ID:"+o.id+"/n/nL:"+nLt+" T:"+nTp+"/nW:"+o.offsetWidth+" H:"+o.offsetHeight);
- }
- </script>
- </head>
- <body>
- <p style="height:100px;margin:0;padding:0;background:#00f;color:#fff;line-height: 100px;text-align:center;">此色块高:100px;</p>
- <div >
- <div >
- <ul>
- <li><input type="text" value="无法取到橙黄色的边框线宽度(border:10px solid #f90;)" size="60" /></li>
- <li><input type="text" value="" size="60" onclick="GetXYWH(this)" /></li>
- <li><input type="text" value="GetXYWH(this);" onclick="GetXYWH(this)" size="60" /></li>
- <li><input type="text" value="GetXYWH(this);" onclick="GetXYWH(this)"size="60" /></li>
- <li><input type="text" value="GetXYWH(Obj('BM'));'BM'));" size="60" onclick="GetXYWH(Obj('BM'));' BM'))" /></li>
- </ul>
- </div><!--BS-->
- <div>
- <p>测试</p>
- <p>测试</p>
- <p>测试</p>
- <p>测试</p>
- <p>测试</p>
- </div><!--BM-->
- </div>
- </body>
- </html>
获取任意Html元素与body之间的偏移距离 offsetTop、offsetLeft
最新推荐文章于 2022-03-09 14:22:57 发布