IE8 inserting text to textarea problem

2019-07-16 05:26发布

问题:

I have some code to insert tags to textarea (for Internet Explorer). But I have problem with IE8. If there is lots of text and I try to insert text somewhere in the end - it's scrolled up.

Code:

<script type="text/javascript">
function bold()
{
    var text1 = document.getElementById('text1');
    var sel = '';
    if (document.selection) 
    {
        sel = document.selection.createRange();
        sel = sel.text;
    }
    if(sel)
    {
        text1.focus();
        document.selection.createRange().text = '<strong>' + sel + '</strong>';
    }
}
</script>

<textarea id="text1" rows="10" style="width:100%;"></textarea>
<br />
<input type="button" value="bold" onclick="bold();" />

It's happens only if I set width to textarea, so code works ok with this markup:

<textarea id="text1" rows="10" cols="80"></textarea>

回答1:

Two options:

  • Manipulate the scrollTop property to move the scrollbar to the end:
    text1.scrollTop = text1.scrollHeight;
  • Move the caret to the desired position using the moveStart() method.