Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - jQuery Get Position of Character in a Div?

Hi Guys [and girls] :)

Just wondering whether it's possible to get the absolute positiong of a character within a div ?

<div class="mycooldiv">
    bunch of text is in here and for example some # and some other cool #
</div>

i.e. using jQuery UI Position perhaps or otherwise - how would I get for example the position of # ?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

If your element only contains text, you can wrap the character in an inline element, and get the position of the element using .offset(). Then, place the original text back. Fiddle: http://jsfiddle.net/Dp6JR/

var $elem = $('.mycooldiv');
var text = $elem.html();
var newText = text.replace(/#/, '<span class="get-position-of-it"></span>');
$elem.html(newText); //Set wrapper
var offset = $(".get-position-of-it").offset();
$elem.html(text)    ; //Place back
var topPos = offset.top;
var left = offset.left;

Note: This function gets the position of the first found # character. If you want to get the position of all characters, add g to the Regular expression (/#/g).

Getting all positions - Fiddle: http://jsfiddle.net/Dp6JR/1/

The offsets of all characters will be stored in a 2-dimensional array (matrix).

var positions = [];
var $elem = $('.mycooldiv');
var text = $elem.html();
var newText = text.replace(/#/g, '<span class="get-position-of-it"></span>');
$elem.html(newText); //Set wrapper
$(".get-position-of-it").each(function(){
    var offset = $(this).offset();
    positions.push([offset.left, offset.top]);
});
$elem.html(text)    ; //Place back
//`positions` is an array of all offset information

The output can be equivalent to:

var positions = [
    [0, 0],
    [100, 0]
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...