Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - Left offset of an inline element using jQuery

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's what's happening:

Diagram

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.

Example usage:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...