HTML textarea; scroll vertically to text
I have an HTML textarea:
<textarea>
Some text
Another text 开发者_如何学Pythonin another line
BOOM
Hello there.
</textarea>
I want to be able to vertically scroll to the word BOOM so that it is visible (it doesn't matter on which line it appears).
Is this possible?
There's actually a way to do this using window.find()
and some variation for IE browsers.
Here's what I came up with so far:
var gotoText = function(text) {
function iefind(string) {
var txt = document.body.createTextRange();
if (txt.findText(string)) {
txt.scrollIntoView();
txt.collapse(false);
}
}
if(!window.find) { // ie
iefind(text);
return;
}
// a double window.find() for backwards and forward search
if(!window.find(text, false, true)){
window.find(text, false, false);
}
};
$('textarea').animate({ 'scrollTop': 30 });
of course 30 is working for my own example with my cols and rows. so find the the right value for yourself.
Note to self:
There is no way of calculating the scroll height which a particular word is at however if you set a fixed value as your css line-height then you can see the story from the point of view that of boom is on for example the 4th line then its scroll height value is 4x (x:line-height) but i can't really right now be bothered to check how good that will work when someone zooms in the browser. but worth a try for you as you have the case.
But how do I know that BOOM is 30 from the top?
Create a <div>
, add it to the page and style it with exactly the same font, white-space
, dimensions, border, padding and overflow as the <textarea>
object. Wrap the ‘BOOM’ in a <span>
, and measure the position of the span relative to the position of the div.
(This isn't a lot of fun.)
It's possible with some javascript! Even if I'm late I hope it can be usefull to someone else!
I published an answer here:
http://blog.blupixelit.eu/scroll-textarea-to-selected-word-using-javascript-jquery/
It works perfectly with jsut one needed rule: Set a line-height n the css of the textarea!
It calculate the position of the word to scroll to just by doing some simple mathematic calculation and it worked perfectly in all my experiments!
Feel free to ask me anything you need about the code!
精彩评论