题目一:
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。