JQuery 獲得絕對,相對位置的座標方法--非常重要

瓜瓜東西發表於2014-08-14
獲取頁面某一元素的絕對X,Y座標,可以用offset()方法:(body屬性設定margin :0;padding:0;)
<iframe height="250" marginheight="0" src="http://pos.baidu.com/acom?adn=3&amp;at=103&amp;aurl=&amp;cad=1&amp;ccd=32&amp;cec=gb2312&amp;cfv=13&amp;ch=0&amp;col=zh-cn&amp;conOP=0&amp;cpa=1&amp;dai=2&amp;dis=0&amp;ltr=http%3A%2F%2Fwww.baidu.com%2Fs%3Fwd%3D%25E8%258E%25B7%25E5%258F%2596%2520div%2520%25E7%25BB%259D%25E5%25AF%25B9%25E5%259D%2590%25E6%25A0%2587%26ie%3Dutf-8%26tn%3Dbaiduhome_pg%26f%3D8%26rsv_bp%3D1%26rsv_spt%3D3%26inputT%3D17014%26rsv_sug3%3D70%26rsv_sug4%3D8944%26rsv_sug1%3D9%26rsv_sug2%3D0%26bs%3Djquery%2520%25E7%25A7%25BB%25E5%258A%25A8div&amp;ltu=http%3A%2F%2Fwww.jb51.net%2Farticle%2F22081.htm&amp;lunum=6&amp;n=jb51_cpr&amp;pcs=1278x530&amp;pis=10000x10000&amp;ps=492x792&amp;psr=1536x864&amp;pss=1278x746&amp;qn=123249acf7076e08&amp;rad=&amp;rsi0=300&amp;rsi1=250&amp;rsi5=4&amp;rss0=%23FFFFFF&amp;rss1=%23F7FCFF&amp;rss2=%23006699&amp;rss3=%23333333&amp;rss4=%23333333&amp;rss5=&amp;rss6=%23e10900&amp;rss7=&amp;scale=&amp;skin=&amp;td_id=91397&amp;tn=text_default_300_250&amp;tpr=1407988815172&amp;ts=1&amp;xuanting=0&amp;dtm=BAIDU_DUP2_SETJSONADSLOT&amp;dc=2&amp;di=u91397" frameborder="0" width="300" allowtransparency="" marginwidth="0" scrolling="no" align="center,center"></iframe>
var X = $('#DivID').offset().top;
var Y = $('#DivID').offset().left;
獲取相對(父元素)位置:
var X = $('#DivID').position().top;
var Y = $('#DivID').position().left;

複製程式碼 程式碼如下:

<!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>java Test</title>
</head>
<style type="text/css">
<!--
body,div { margin:0; padding:0;}
-->
</style>
<script type="text/javascript" src="js/jquery.js"></script>

<body>
<div style="background:#ccc;height:300px;" onclick=""></div>
<div style="position:relative;">
<div style=" position:absolute;left:50px; top:50px;" id="DivID"></div>
</div>
<script type="text/javascript">
var X = $('#DivID').offset().top;
var Y = $('#DivID').offset().left;
document.write(X+"<br />");
document.write(Y+"<br />");
//獲取相對(父元素)位置:
var C = $('#DivID').position().top;
var D = $('#DivID').position().left;
document.write(C+"<br />");
document.write(D);
</script>
</body>
</html> 

相關文章