JS:在Div中获取字符串的Y位置

时间:2013-10-15 22:54:18

标签: javascript jquery html css

长话短说,我想在我的Html div中创建一个非常基本的搜索。 每个可能的搜索标记都以$开头和结尾。每个标签都是唯一的。

我的目标是创建一个带标签的功能,搜索div,找到div中该标签的行(Y位置)。

唯一的问题是获取字符串的行位置。我可以找到字符串是否存在,但我没有关于它在div中的位置的信息。

(在示例中,它由getLineWhereTagIsFound(tag)表示。)

注意:在找到标签之前,我可能会计算<br>的数量,但我不知道它有多可靠。

这是我到目前为止所做的。

    <div id="helpText" class='onlyTextScroll container'>        
        $Fruits$<br>
        Fruits are very nice.<br>
        Fruits are very nice.<br>
        Fruits are very nice.<br>
        Fruits are very nice.<br>
        Fruits are very nice.<br>
        Fruits are very nice.<br>
        Fruits are very nice.<br>
        Fruits are very nice.<br>
        <br>
        $Vegetables$<br>
        Vegetables are very evil.<br>
        Vegetables are very evil.<br>
        Vegetables are very evil.<br>
        Vegetables are very evil.<br>
        Vegetables are very evil.<br>
        Vegetables are very evil.<br>
        Vegetables are very evil.<br>
        <br>
    </div>


<script>
function updateHelp(tag){
    var y = getLineWhereTagIsFound('$' + tag + '$');
    y *= lineHeight;
    $("#helpText").scrollTop(y);

}
/* Example
function updateHelp('Vegetables'){
    var y = getLineWhereTagIsFound('$' + 'Vegetables' + '$');
    //y would be 10 because $Vegetables$ is found on line 10; 
    //let say lineHeight is 10;     
    y = y*lineHeight; //10*10

    $("#helpText").scrollTop(100);

}
*/
</script>

1 个答案:

答案 0 :(得分:0)

function getLineWhereTagIsFound(tag){
    var helpText = document.getElementById("helpText");
    var count = 0;
    for(var i=0;i<helpText.childNodes.length;i++){
        if(helpText.childNodes[i].nodeType==3){
            count++;
            if(helpText.childNodes[i].nodeValue.indexOf(tag)>=0){
                break;
            }
        }
    }
    return count;
    //count would be 11,not 10, because $Vegetables$ is found on line 11
    //each <br/> one line
}