获取浮动元素的位置
我有一些这样的代码:
<style>
.box {
width: 100px;
height: 100px;
margin: 10px;
background: green;
border: 1px solid black;
float: left;
}
#wrapper {
position: relative;
}
</style>
<div id="wrapper">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
<div class="box">6</div>
</div>
我需要获得每个框相对于#wrapper 的左侧、顶部。我试图通过 jQuery.position() 来做到这一点,但是我没有得到正确的结果。继续得到0,0。其他人都可以吗我认为这里的问题是浮动......如果这些是绝对定位的,我会正确地读取它们。
I have some code like this:
<style>
.box {
width: 100px;
height: 100px;
margin: 10px;
background: green;
border: 1px solid black;
float: left;
}
#wrapper {
position: relative;
}
</style>
<div id="wrapper">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
<div class="box">6</div>
</div>
I need to get the left,top of each of the boxes relative to #wrapper. I'm trying to do this through jQuery.position() however, I am not getting the right results. Keep getting 0,0. Can anybody else. I think the problem here is floats... if these were absolutely positioned, I would be reading them correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里有一些 jQuery 代码,它将提醒左侧位置。这与浮动效果很好。
这里有一个jsFiddle: http://jsfiddle.net/ytGYS/
Here some jQuery code which will alert the left position. This works with floating well.
here a jsFiddle: http://jsfiddle.net/ytGYS/
位置实际上工作得很好,只需确保你明确修复你的#wrapper,使其具有高度和宽度。您遇到的问题是,当所有元素都浮动时,您的父级 #wrapper 会折叠并且没有尺寸,因此 jQuery 无法计算出一个元素与另一个元素之间的距离。
Position actually works fine, just make sure you clearfix your #wrapper so that it has a height and width. The problem you're having is that with all of the elements floated, your parent #wrapper gets collapsed and has no dimensions, so jQuery can't figure out how far one thing is from the other.
这是您的标记和代码示例的小提琴: http://jsfiddle.net/tBwwr/
Here's a fiddle with your mark-up and a code example: http://jsfiddle.net/tBwwr/
andrewheins 的回答+1:
你完全正确;如果 #wrapper 太小而无法显示所有相邻的浮动元素,则 $().offset() 将为您提供彼此相邻的元素的位置。
烦人的事情是在 #wrapper 获取正确宽度之前检查 $().offset() 。例如,如果有两个 $(document).ready() 函数以错误的顺序执行。 (首先获取 offset(),然后设置宽度)
注意:我没有足够的声誉来投票支持他的答案或发表评论。
+1 for andrewheins answer:
You are totally right; if the #wrapper is too small to display all the floated elements next to each other, the $().offset() will give you the position of the elements one under each other.
The annoying thing is when the $().offset() is checked before the #wrapper gets is correct width. For example if there are two $(document).ready() functions which are executed in the wrong order. (first get offset(), then set width)
Note: I have not enough reputation to vote his answer up or leave a comment.