1

长话短说,我想在我的 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>
4

1 回答 1

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
}
于 2013-10-27T17:23:50.170 回答