如何用jquery获取元素在文档中位置?

大狗狗 2020-07-18 10:40:47
有一个固定大小的容器(div),然后我在其中添加了多个固定大小的子div,我想获取这样一个值:某个子元素距第0号子元素的距离。使用jquery offset或position方法得到的似乎都是子元素距某个父容器上沿的距离(滚动条位置不同,值也不同)。而我所要的值和滚动条位置是无关的。无奈我只好通过累加子元素高度的笨办法来达到目的(.prevAll().each(...)下面代码中没有列出)。还有更好办法吗?下面是我测试代码:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
</head>

<body>
<div id="title" style="width:100px;height:30px;line-height:30px;text-align:center;border:#aaa solid 1px;background-color:#f5f5f5;"></div><br />
child index :<input type="text" id="index" style='width:40px;'> <button onclick="fun1()">get top (offset , postion)</button><br /><br />
<div id="con" style="width:420px;height:500px;border:#aaa solid 1px;overflow-y:scroll;"></div>

<script>
for(var i=0;i<10;++i){
$("#con").append("<div style='width:380px;height:198px;border:#00f dotted 1px;margin-left:8px;background-color:#f5f5f5;'>"+i+"</div>");
}

function fun1()
{
$("#title").text($("#con").children().eq(parseInt($("#index").val())).offset().top+","+$("#con").children().eq(parseInt($("#index").val())).position().top);
}
</script>
</body>
</html>

...全文
1486 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
大狗狗 2020-07-18
  • 打赏
  • 举报
回复
非常感谢!!
chenrynet 2020-07-18
  • 打赏
  • 举报
回复
高度不固定版本的 <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.6.4.min.js"></script> </head> <body> <div id="title" style="width:100px;height:30px;line-height:30px;text-align:center;border:#aaa solid 1px;background-color:#f5f5f5;"></div><br /> child index :<input type="text" id="index" style='width:40px;'> <button onclick="fun1()">get top (offset , postion)</button><br /><br /> <div id="con" style="width:420px;height:500px;border:#aaa solid 1px;overflow-y:scroll;"></div> <script> for(var i=0;i<10;++i){ $("#con").append("<div style='width:380px;height:198px;border:#00f dotted 1px;margin-left:8px;background-color:#f5f5f5;'>"+i+"</div>"); } var con=document.querySelector("#con"); //获取父级元素 也可以不用这部 var child=con.querySelectorAll('div'); //获取子元素的nodelist function fun1() { var tops=child[1].getBoundingClientRect().top; //第二个元素顶部距离浏览器窗口顶部的距离 可以当做第一个元素的底部位置 var index=document.querySelector('#index').value; //索引值 var mytops=child[index].getBoundingClientRect().top; //第N个元素距离浏览器窗口顶部的距离 console.log(mytops-tops); // $("#title").text($("#con").children().eq(parseInt($("#index").val())).offset().top+","+$("#con").children().eq(parseInt($("#index").val())).position().top); } </script> </body> </html>
chenrynet 2020-07-18
  • 打赏
  • 举报
回复
既然固定大小了 你是不是可以直接用子元素的高度乘以(index-1)

87,995

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧