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

大狗狗 CSDN会员 大狗狗 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
有一个固定大小的容器(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>

...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
大狗狗 CSDN会员
JavaScript 87,984 成员 224,681 内容