jQuery获得页面元素的绝对/相对位置即绝对X,Y坐标

2014-03-06 45

获取页面某一元素的绝对X,Y坐标,可以用offset()方法:

<span style="color:#000066; font-weight:bold">var</span> X <span style="color:#339933">=</span> $<span style="color:#009900">(</span><span style="color:#3366CC">'#DivID'</span><span style="color:#009900">)</span>.<span style="color:#660066">offset</span><span style="color:#009900">(</span><span style="color:#009900">)</span>.<span style="color:#660066">top</span><span style="color:#339933">;</span> 
<span style="color:#000066; font-weight:bold">var</span> Y <span style="color:#339933">=</span> $<span style="color:#009900">(</span><span style="color:#3366CC">'#DivID'</span><span style="color:#009900">)</span>.<span style="color:#660066">offset</span><span style="color:#009900">(</span><span style="color:#009900">)</span>.<span style="color:#660066">left</span><span style="color:#339933">;</span>

获取相对(父元素)位置:
<span style="color:#000066; font-weight:bold">var</span> X <span style="color:#339933">=</span> $<span style="color:#009900">(</span><span style="color:#3366CC">'#DivID'</span><span style="color:#009900">)</span>.<span style="color:#660066">position</span><span style="color:#009900">(</span><span style="color:#009900">)</span>.<span style="color:#660066">top</span><span style="color:#339933">;</span> 
<span style="color:#000066; font-weight:bold">var</span> Y <span style="color:#339933">=</span> $<span style="color:#009900">(</span><span style="color:#3366CC">'#DivID'</span><span style="color:#009900">)</span>.<span style="color:#660066">position</span><span style="color:#009900">(</span><span style="color:#009900">)</span>.<span style="color:#660066">left</span><span style="color:#339933">;</span>
展开阅读全文

更多Javascript文章

IE与Firefox在JavaScript上的7个不同句法分享
Oct 30 38
JavaScript 32位整型无符号操作示例
Dec 08 34
js 动态添加元素(div、li、img等)及设置属性的方法
Jul 19 42
JavaScript中数组常见操作技巧
Sep 01 38
详解Vue用自定义指令完成一个下拉菜单(select组件)
Oct 31 33
使用pm2自动化部署node项目的方法步骤
Jan 28 42
layui layer select 选择被遮挡的解决方法
Sep 21 64
手机访问当前页面