JavaScript实现元素定位与坐标获取
作者:像素漫游时间:2026-10-28 15:26:41浏览:560
本文通过一个JavaScript实例,演示如何操作元素定位。利用getBoundingClientRect方法获取元素边界矩形信息,结合offsetParent递归计算,实现精确定位。代码包含HTML结构与CSS样式,适用于需要动态获取元素绝对坐标的开发场景。
JavaScript元素定位示例
在Web开发中,使用JavaScript来操作和定位元素是一个高效的选择。以下提供一个具体的代码示例,供有相关需求的开发者参考。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>每天一个JavaScript实例-操作元素定位元素</title>
<style>
div#a{
width:500px;
}
div{
border:1px solid #000;
padding:10px;
}
#cursor{
position:absolute;
background-color:#ff0;
width:20px;
height:20px;
left:50px;
top:300px;
}
</style>
<script>
function positionObject(obj){
var rect = obj.getBoundingClientRect();
return [rect.left,rect.top];
}
window.onload = function(){
var tst = document.documentElement.getBoundingClientRect();
alert(tst.top);
var cont = 'A';
var cursor = document.getElementById("cursor");
while(cont){
cont = prompt("where do you want to move the cursor block?","A");
if(cont){
cont = cont.toLowerCase();
if(cont == "a"||cont=="b"||cont=="c"){
var elem = document.getElementById(cont);
var pos = positionObject(elem);
console.log(pos);
cursor.setAttribute("style","top:"+pos[1]+"px;"+"left:"+pos[0]+"px");
}
}
}
}
</script>
</head>
<body>
<div id = "a">
<p>A</p>
<div id ="b">
<p>B</p>
<div id="c">
<p>C</p>
</div>
</div>
</div>
<div id="cursor">
</div>
</body>
</html>
作者最新文章
D3.js 处理大规模数据点的性能优化策略
2026-11-05 15:37:25
JS实现网页摄像头实时扫码:结合getUserMedia与jsQR教程
2026-11-05 15:27:28
D3.js v5 迁移到 v7 的 API 变更与注意事项
2026-11-05 11:57:17
使用 animate.js 实现多元素协同的序列动画
2026-11-04 22:27:53
JS拖拽排序时怎么添加平滑动画效果?FLIP技术实战
2026-11-04 10:12:22
