jQuery:将textarea滚动到给定位置

我有一个textarea,有很多很多文字:

 

我想向下滚动textarea,这样用户就可以看到第2000个字符了。 我怎么能用javasctipt / jQuery做到这一点?

 $('#txt').scrollToCharNo(2000); // something like this would be great 

编辑(我的解决方案)

好吧,我设法让它自己工作。 我发现的唯一方法是创建一个与textarea具有相同字体和宽度的DIV,将SPAN放在所需字符附近并找到该跨度的位置。

我相信,有人可能会发现我的解决方案很有用,所以我会在这里粘贴它:

 jQuery.fn.scrollToText = function(search) { // getting given textarea contents var text = $(this).text(); // number of charecter we want to show var charNo = text.indexOf(search); // this SPAN will allow up to determine given charecter position var anch = ''; // inserting it after the character into the text text = text.substring(0, charNo) + anch + text.substring(charNo); // creating a DIV that is an exact copy of textarea var copyDiv = $('
') .append(text.replace(/\n/g, '
')) // making newlines look the same .css('width', $(this).attr('clientWidth')) // width without scrollbar .css('font-size', $(this).css('font-size')) .css('font-family', $(this).css('font-family')) .css('padding', $(this).css('padding')); // inserting new div after textarea - this is needed beacuse .position() wont work on invisible elements copyDiv.insertAfter($(this)); // what is the position on SPAN relative to parent DIV? var pos = copyDiv.find('SPAN#anch').offset().top - copyDiv.find('SPAN#anch').closest('DIV').offset().top; // the text we are interested in should be at the middle of textearea when scrolling is done pos = pos - Math.round($(this).attr('clientHeight') / 2); // now, we know where to scroll! $(this).scrollTop(pos); // no need for DIV anymore copyDiv.remove(); }; $(function (){ $('#scroll_button').click( function() { // scrolling to "FIND ME" using function written above $('#txt').scrollToText('FIND ME'); return false; } ); });

这是一个演示(它的工作原理!): http : //jsfiddle.net/KrVJP/

由于没有一个答案真正解决了问题,我会接受experimentX的答案:谢谢你努力帮助我,我很感激!

我不确定它是否有用。 请在这里查看 。 它似乎在第2000,第1500和第1000位工作。

编辑混淆字体大小或行高???

  $(function (){ var height = 2000/$('#txt').attr('cols'); $('#txt').scrollTop(height*13); $('#txt').selectRange(2000,2000); //this is just to check }); $.fn.selectRange = function(start, end) { //this is just to check return this.each(function() { if (this.setSelectionRange) { this.focus(); this.setSelectionRange(start, end); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } }); }; 

更新这个怎么样

  var height = 1200/$('#txt').attr('cols'); var line_ht = $('#txt').css('line-height'); line_ht = line_ht.replace('px',''); height = height*line_ht; 

您可以使用此 jquery插件