我有一个包含很多文本的文本区域:
<textarea cols="50" rows="10" id="txt">lots and lots of text goes here</textarea>
我想向下滚动文本区域,以便用户可以看到第 2000 个字符。我如何使用 javasctipt/jQuery 来做到这一点?
$('#txt').scrollToCharNo(2000); // something like this would be great
编辑(我的解决方案)
好吧,我自己设法让它发挥作用。我发现的唯一方法是创建一个与文本区域具有相同字体和宽度的 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 = '<span id="anch"></span>';
// 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 = $('<div></div>')
.append(text.replace(/\n/g, '<br />')) // 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/ http://jsfiddle.net/KrVJP/
由于没有一个答案真正解决了问题,我会接受experimentX的答案:感谢您为帮助我付出的努力,我很感激!