У меня есть текстовое поле с очень-большим количеством текста :
<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/
Поскольку ни один из ответов на самом деле не решил проблему, я приму ответ от ExperimentX: спасибо, что приложили усилия, чтобы помочь мне, я ценю это!