offset() :
获取匹配元素在当前窗口的相对偏移。位置是相对屏幕的,返回的对象包含两个整形属性:top 和 left。此方法只对可见元素有效。
DEMO:
<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>position()</title> <style type="text/css"> * { margin:0px; padding:0px; } p { font-size:12px; height:40px; background:red; } </style> <script type="text/javascript" src="js/jquery-1-4.js"></script> <script type="text/javascript"> $(function() { var p = $("p:last"); var offset = p.offset(); $("span").html( "left: " + offset.left + ", top: " + offset.top ); }); </script> </head> <body> <p>first one</p><p>second one</p>
<p>third one</p>
<span></span>
</body> </html>position() :
获取匹配元素相对父元素的偏移。相对于父元素,并且父元素和子元素恤是绝对定位。
返回的对象包含两个整形属性:top 和 left。为精确计算结果,请在补白、边框和填充属性上使用像素单位。此方法只对可见元素有效。DEMO:
<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>position()</title> <style type="text/css"> * { margin:0px; padding:0px; } p { font-size:12px; height:40px; background:red; } .pardentBox { width:500px; height:400px; margin-left:0px; margin-top:0px; background:#FF6699; position:relative; } .innerBox { width:200px; height:100px; background:#CC0033; position:absolute; left:60px; top:100px; } </style> <script type="text/javascript" src="js/jquery-1-4.js"></script> <script type="text/javascript"> $(function() { var innerBox = $(".innerBox"); var position =innerBox.position(); $("span").html( "left: " + position.left + ", top: " + position.top ); }); </script> </head> <body> <div class="pardentBox"> parent box <div class="innerBox"> inner box </div> </div> <span></span> </body> </html>