最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML textarea; scroll vertically to text - Stack Overflow

programmeradmin3浏览0评论

I have an HTML textarea:

<textarea>
Some text
Another text in 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?

I have an HTML textarea:

<textarea>
Some text
Another text in 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?

Share Improve this question asked Mar 24, 2010 at 11:02 Luca MatteisLuca Matteis 29.3k22 gold badges116 silver badges172 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

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!

发布评论

评论列表(0)

  1. 暂无评论