获取容器div上下文中span中字符的坐标



下面是一个例子,我想要的词"标准"的坐标是在第二个span使用javascript/jquery。

HTML:

<div class="container">
        <span>Some text is here</span>
        <span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>
        <span>Some text is here too.</span>
        <span>Some text is here too.</span>
        <span>Some text is here too.</span>
        <span>Some text is here too.</span>
    </div>
CSS:

.container{
    position: relative;
    padding: 100px;
}
span{
     position:relative;
    float:left;
    padding:10px;
}
http://jsfiddle.net/P7rs4/1/

要获得一个单词的坐标,必须首先将它包装在一个元素中

$('.container').html(function(_, html) {
    return html.replace('standard', '<span class="standard">standard</span>');
});

然后你得到该元素相对于文档的offset()位置,或者相对于父元素的position()位置

var position = $('.standard').offset();

小提琴

抱歉编辑

var field = $('.container > span').filter(function (){
        return $(this).text().contains('standard');
});
var position = field.position();

基本上它将获得所有具有文本标准的元素,所以它可以多于一个。因此,实际的解决方案是循环结果,然后获得位置。

最新更新