使用 jQuery 内联元素的左偏移量
我有以下 HTML 片段:
<div><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit <strong id="s">esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</strong></p></div>
使用 CSS 将 DIV 的宽度固定为 600px。 现在,我想找到 元素的 offset().left 。 所以我这样做了:
alert( $("#s").offset().left );
但是这似乎没有产生正确的值,因为我可以清楚地看到强元素在 600px 宽度的一半处可见,但我得到的偏移值只有 8px。
如何我是否找到内联强元素的 offset().left 值?
I have the following piece of HTML:
<div><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit <strong id="s">esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</strong></p></div>
The width of the DIV is fixed at 600px using CSS. Now, I want to find the offset().left of the <strong>
element. So I did:
alert( $("#s").offset().left );
However this does not seem to produce the right value, as I can clearly see the strong element is seen half way through the 600px width, but the offset value I get is only 8px.
How do I find the offset().left value of the inline strong element?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是发生的事情:
由于内联元素跨越多行,jQuery 将为您提供该元素的最左边位置,而不是元素开头的偏移量。
要解决这个问题,请尝试这个插件:
该插件将创建一个临时元素并将其插入到目标元素之前 - 然后它将返回该临时元素的偏移量。
用法示例:
Here's what's happening:
Since the inline element spans multiple lines jQuery will give you the left-most position of that element, not the offset of the beginning of the element.
To get around this, try this plugin:
The plugin will create a temporary element and insert it just before the target element - it will then return the offset of that temporary element.
Example usage:
你得到 8px 结果的原因是因为即使元素从容器的一半开始,由于有一个换行符,它的左边缘距页面 8px。
我有一种感觉,可能有比这更好的方法,但我能想到解决这个问题的第一件事就是在
并检查其位置:
The reason you are getting the result of 8px is because even though the element starts in half way through your container, since there's a line break its left edge is 8px in from the page.
I have one of those feelings that there's probably a much better way to do it than this, but the first thing I could think of to work around this problem is to insert another element right before the
<strong>
and check its position:我相信偏移量是相对于文档的,而位置是相对于父级的。
http://docs.jquery.com/CSS/position
I believe offset is relative to the document, while position is relative to the parent.
http://docs.jquery.com/CSS/position