jquery獲取div距離窗口和父級dv的距離示例
更新時間:2013年10月10日 16:24:20 作者:
jquery中jquery.offset().top/left用于獲取div距離窗口的距離而jquery.position().top/left用于獲取距離父級div的距離,下面有個不錯的示例,感興趣的朋友可以參考下
jquery中jquery.offset().top / left用于獲取div距離窗口的距離,jquery.position().top / left 用于獲取距離父級div的距離(必須是絕對定位的div)。
(1)先介紹jquery.offset().top / left
css:
復制代碼 代碼如下:
*{ margin: 0px; padding: 0px; }
div{ margin: 0px auto; }
.a{ width: 960px; height: 200px; }
.parentBox{ padding: 30px; margin-top: 40px; width: 960px; height: 300px; }
.innerBox{ padding: 20px; margin-top: 10px; width: 400px; height: 100px; }
html:
復制代碼 代碼如下:
<body>
<div class="a"> a<div>
<div class="parentBox">
<div class="innerBox">innerBox</div>
</div>
</body>
js:
復制代碼 代碼如下:
$(function(){
var_offsetTop = $(".innerBox").offset().top; //280px
})
這里的280px= a.height/200px + parentBox.padding-top/30px + parentBox.margin-top/40px + innerBox.margin-top/10px;
//如果這邊parentBox設置position: relative; innerBox設置position:absolute;并且innerBox設置了top: 40px;
//此時_offsetTop的值為290px = a.height/200px + parentBox.margin-top/40px + innerBox.margin-top/10px + ineBox.top/40px;
//因為絕對定義是以父級div的左上角的內(nèi)邊框為參考坐標的。
//如果innerBox設置了邊框的話還要加上邊框的值
(2)jqury.position().top /left用于獲取子div距離父級div的距離,并且子div必須是絕對定位
css:
復制代碼 代碼如下:
*{ margin: 0px; padding: 0px; }
div{ margin: 0px auto; }
.a{ width: 960px; height: 200px; }
.parentBox{ padding: 30px; margin-top: 40px; width: 960px; height: 300px; position: relative; }
.innerBox{ padding: 20px; margin-top: 10px; width: 400px; height: 100px; position: absolute; }
html:
復制代碼 代碼如下:
<body>
<div class="a"> a<div>
<div class="parentBox">
<div class="innerBox">innerBox</div>
</div>
</body>
js:
復制代碼 代碼如下:
$(function(){
var_offsetTop = $(".innerBox").offset().top; //280px
})
您可能感興趣的文章:
- jquery層級選擇器的實現(xiàn)(匹配后代元素div)
- jQuery實現(xiàn)將div中滾動條滾動到指定位置的方法
- 通過JQuery將DIV的滾動條滾動到指定的位置方便自動定位
- jQuery判斷div隨滾動條滾動到一定位置后停止
- JQuery實現(xiàn)點擊div以外的位置隱藏該div窗口
- jquery獲取div寬度的實現(xiàn)思路與代碼
- 使用JS或jQuery模擬鼠標點擊a標簽事件代碼
- javascript和jquery修改a標簽的href屬性
- Jquery為a標簽的href賦值實現(xiàn)代碼
- jquery觸發(fā)a標簽跳轉事件示例代碼
- jquery 為a標簽綁定click事件示例代碼
- jquery通過a標簽刪除table中的一行的代碼
- jQuery簡單獲取DIV和A標簽元素位置的方法
相關文章
基于Jquery和CSS3制作數(shù)字時鐘附源碼下載(CSS3篇)
數(shù)字時鐘在web倒計時,web鬧鐘效果以及基于html5的web app中,本文給大家介紹基于jquery和css3制作數(shù)字時鐘附源碼下載,感興趣的朋友來看看吧2015-11-11jQuery實現(xiàn)鼠標經(jīng)過提示信息的地圖熱點效果
這是一個升級版本,更新了一個在IE8里的小問題,加入了提示框的內(nèi)容自動換行處理(北京點上有演示)!估計差不多該是最后樣式了。IE6、IE8、谷歌、火狐、測試正常。2015-04-04