jQuery获取字符在Div中的位置? [英] jQuery Get Position of Character in a Div?
问题描述
嗨家伙[和女孩]:)
只是想知道是否有可能获得绝对
positiong of一个字符在div中?
< div class =mycooldiv>
一堆文本在这里,例如一些#和其他一些很酷的#
< / div>
即使用 jQuery UI Position
或许或以其他方式 - 例如,我将如何得到#
?
> .offset()
。然后,放回原文。 小提琴: 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); //设置封装
var offset = $(。get-position-of-it)。offset();
$ elem.html(text); //放回
var topPos = offset.top;
var left = offset.left;
注意:此函数获取第一个找到的位置#
字符。如果你想得到所有字符的位置,向正则表达式(/#/ g
)添加 g
。
取得所有职位 - 小提琴: http://jsfiddle.net/Dp6JR/1/
所有角色的偏移量将会被存储在二维数组(矩阵)中。
var positions = [];
var $ elem = $('。mycooldiv');
var text = $ elem.html();
var newText = text.replace(/#/ g,'< span class =get-position-of-it>< / span>');
$ elem.html(newText); ()函数(){
var offset = $(this).offset();
位置。 push([offset.left,offset.top]);
});
$ elem.html(text); //放回
//`positions`是一个所有抵消信息的数组
输出可以相当于:
var positions = [
[0,0],
[100 ,0]
];
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 #
?
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]
];
这篇关于jQuery获取字符在Div中的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!