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