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

时间:2014-07-24 11:35:50

标签: javascript jquery

下面是我想要单词"标准"的坐标的例子。使用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/

2 个答案:

答案 0 :(得分:4)

要获取单词的坐标,必须首先将其包装在元素中

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

然后,您获得该元素相对于文档的offset()位置,或相对于具有position()

的父元素的位置
var position = $('.standard').offset();

FIDDLE

答案 1 :(得分:0)

对不起已编辑。

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

var position = field.position();

基本上它会使所有元素都符合文本标准,所以它可能不止一个。所以真正的案例解决方案是循环结果,然后获得位置。