在<div>中滚动到给定字符串</div>的第一个匹配项

时间:2012-11-25 04:54:11

标签: javascript jquery scroll

在我的div标签中,有很多行非常长的文本,div元素当前是可滚动的。我想要做的是找到第一次出现的特定字符串并自动滚动到包含该字符串的行。没有换行符或任何类型的字符串分隔符,我可以使用它来轻松逼近滚动位置。

我想我可以这样做:

var max_chars_per_line = approximated max # of chars that can fit into one line;
var font_height = approximated font height in px;
var needle = string to look for;
var haystack = content in the <div> tag;
var index = haystack.indexOf(needle);
var num_lines_to_skip = index / max_chars_per_line;
my_div_tag.scrollTo(num_lines_to_skip * font_height);

我不禁想知道是否有更好的(javascript / jQuery)解决方案。我自己的尽职调查没有发现。

3 个答案:

答案 0 :(得分:1)

如果您的所有文本都在一个div中,那么像这个解决方案就可以了。

var goto = function(str){

    var content = $('#content').html();
    $('#content').html( content.replace(str,'<a name="goto">'+str+'</a>') );
    window.location = '#goto';
}

goto('Whatever your string is here');

http://jsfiddle.net/NmhHH/

答案 1 :(得分:1)

<p id="text">Lorem ipsum ... lots of text.... onion</p>

JQ:

var needle = 'onion';
$('#text').html($('#text').html().replace(needle, '<a id="imhere"></a>'+needle));
$('html,body').animate({scrollTop: $('#imhere').offset().top​}, 500);​​​​​​​​​​​​

演示http://jsfiddle.net/vq7LD/

答案 2 :(得分:-1)

你不能做类似于使用以下Java类型代码的事情:

  var lineToTest = getLine(textArray);

  if(lineToTest.contains(testingLine){
   lineIndex = getLineNumber(textArray-1); //since it already accessed the line it'll have to access the next and subtract 1. }

然后只需使用任何突出显示技术来突出显示该行。你必须显然创建你的getLine,getLineNumber函数。除非有一些很酷的jQuery函数(可能就是这种情况)。