javascript - JS : Get Y Position of a String in Div

标签 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>

最佳答案

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
}

关于javascript - JS : Get Y Position of a String in Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19392472/

相关文章:

jquery - 使 jQuery-ui 可拖动 handle 覆盖整个页面

javascript - 固定页面不可见区域的div

javascript - Material-UI 工具提示 zIndex 在 Select 组件中的 MenuItem

javascript - 一旦获得焦点,将 RadioButton 值设置为 true,然后点击 asp :RadioButton 中的 Enter 按钮

javascript - 如何使用正则表达式和 window.location.href.indexOf() 定位 url 路径中的特定文件夹?

javascript - 如何同时创建ajax请求和背景动画

javascript - 在 Raphael 中复制 d3.js 动态树

javascript - 如何正确从数组中删除对象?

html - 使CSS动画不重启

javascript - 在 Cordova 地理定位中访问模拟蓝牙 GPS 坐标