使用jQuery左侧偏移内联元素 [英] Left offset of an inline element using jQuery

查看:136
本文介绍了使用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。现在,我想找到< strong> 元素的offset()。left。所以我做了:

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 );

然而这似乎没有产生正确的价值,因为我可以清楚地看到强者在600px宽度的中间看到了元素,但是我得到的偏移值只有8px。

如何找到offset()。left value内联强元素?

How do I find the offset().left value of the inline strong element?

推荐答案

以下是发生的事情:

由于内联元素跨越多行jQuery将给出该元素的最左侧位置,而不是元素开头的偏移量。

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:

jQuery.fn.inlineOffset = function() {
    var el = $('<i/>').css('display','inline').insertBefore(this[0]);
    var pos = el.offset();
    el.remove();
    return pos;
};

该插件将创建一个临时元素并将其插入目标元素之前 - 它将返回该临时元素的偏移量。

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.

示例用法:

alert( jQuery('strong').inlineOffset().left );

这篇关于使用jQuery左侧偏移内联元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆