计算元素直到偏移

时间:2013-12-04 06:25:44

标签: jquery html

我有一些类似的代码:

<div id="content">
<span class="pivot">1</span>
Some pure text here
<span class="pivot">2</span>
Some pure text here
<span class="pivot">3</span>
Some pure text here
<span class="pivot">4</span>
TEXT FOR SELECTION
<span class="pivot">5</span>
Some pure text here
</div>

我的问题:

  • 我通过鼠标
  • 选择文本“TEXT FOR SELECTION”
  • 我想在TEXT FOR SELECTION之前计算PIVOT类的跨度

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

每个元素,文本或范围都是childNode。因此,如果您获得了您选择的childNode的索引并减去1,那么您将获得答案。但是,如果鼠标进入childNode,我不确定是否有办法捕获。

所以我认为你用span来包围所有元素会更好,然后添加onMouseOver="getIndex(this)"来获取孩子的索引。

function getIndex(child){
    var children = document.getElementById("content").children;

    for(i = 0; i < children.length; i++)
        if(child == children[i])
        alert("Element number " + i)
}

和内容就像;

<div id="content">
    <span class="pivot" onmouseover="getIndex(this)">1</span>
    <span onmouseover="getIndex(this)">Some pure text here</span>
    <span class="pivot" onmouseover="getIndex(this)">2</span>
    <span onmouseover="getIndex(this)">Some pure text here</span>
    <span class="pivot" onmouseover="getIndex(this)">3</span>
    <span onmouseover="getIndex(this)">Some pure text here</span>
    <span class="pivot" onmouseover="getIndex(this)">4</span>
    <span onmouseover="getIndex(this)">TEXT FOR SELECTION</span>
    <span class="pivot" onmouseover="getIndex(this)">5</span>
    <span onmouseover="getIndex(this)">Some pure text here</span>
</div>

答案 1 :(得分:0)

您只需要像这样修改HTML:

<div id="content" onmouseup="selectText()">
<span class="pivot">1</span>
Some pure text here
<span class="pivot">2</span>
Some pure text here
<span class="pivot">3</span>
Some pure text here
<span class="pivot">4</span>
TEXT FOR SELECTION
<span class="pivot">5</span>
Some pure text here
</div>

你需要编写脚本:

function selectText(element) {
        if (window.getSelection) {
            var selection = window.getSelection();  
            if(selection.extentNode.data.trim() == "TEXT FOR SELECTION"){
                var counter = 0;
                var a = $('#content')[0].childNodes;
                for(var i=0;i<a.length;i++){                
                    var check=a[i];
                    if(check.data != undefined && check.data.trim() == "TEXT FOR SELECTION"){
                        break;
                    }
                    if(check.data == undefined)
                        counter++;
                }
                alert(counter);
            }        
        }
    }

您将获得警报数量的span标记。