And*_*ndy 3 html jquery position
嗨,伙计们 [和女孩们] :)
只是想知道是否可以absolute在 div 中获取字符的位置?
<div class="mycooldiv">
bunch of text is in here and for example some # and some other cool #
</div>
Run Code Online (Sandbox Code Playgroud)
即使用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); //Set wrapper
var offset = $(".get-position-of-it").offset();
$elem.html(text) ; //Place back
var topPos = offset.top;
var left = offset.left;
Run Code Online (Sandbox Code Playgroud)
注意:此函数获取第一个找到的#字符的位置。如果要获取所有字符的位置,请添加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); //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
Run Code Online (Sandbox Code Playgroud)
输出可以等价于:
var positions = [
[0, 0],
[100, 0]
];
Run Code Online (Sandbox Code Playgroud)