題目一:
JavaScript 獲取div在頁面中坐標
以div為例,獲取一個元素在頁面中的位置。
代碼和
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<style type="text/css">
*{padding:0px;margin:0px;
}
#thediv{width:100px;height:125px;margin:200px;background:green;text-align:center;font-size:12px;line-height:125px;
}
</style>
<script type="text/javascript">
function getIE(e,show){//此函數可以獲取響應對象在頁面的位置,并將位置顯示在指定元素中,第一個參數是要獲取位置的元素對象,第二個參數是顯示位置的元素對象。var t=e.offsetTop;//返回元素距離最近定位父級元素頂部的距離,如果父級中沒有定位元素,則返回距離body頂端的距離var l=e.offsetLeft;//返回元素距離最近定位父級元素左部的距離,如果父級中沒有定位元素,則返回距離body左端的距離。while(e=e.offsetParent){t+=e.offsetTop;l+=e.offsetLeft;}//因為有可能元素是被多層嵌套的,所以相關距離需要進行疊加。show.innerHTML="top="+t+"/nleft="+l;//將位置數據寫入指定對象。}
window.onload=function(){var odiv=document.getElementById("thediv");var oshow=document.getElementById("show");getIE(odiv,oshow)
}
</script>
</head>
<body>
<div id="show">測試</div>
<div id="thediv">測試</div>
</body>
</html>
相關知識:
(1).offsetTop屬性參閱JavaScript offsetTop。
(2).offsetParent屬性參閱JavaScript offsetParent。