开发者

Textarea replace value scrollHeight in Firefox

开发者 https://www.devze.com 2023-03-03 21:32 出处:网络
I am implementing tag insertion in textarea. Everything is working great. But. In Firefox if text height is bigger than textarea, when scrollbar appears. After tag replacement, it jumps to the beggi

I am implementing tag insertion in textarea. Everything is working great.

But.

In Firefox if text height is bigger than textarea, when scrollbar appears. After tag replacement, it jumps to the begging of the text area. All other browsers stay where replacement took place.

Is it possible to make this in Firefox?

IE has its own implementation. Firefox, Opera and Chrome use

var len = textarea[0].value.length
var start = textarea[0].selectionStart;
var end = textarea[0].selectionEnd;
var sel = textarea[0].value.substring(start, end);
var replace = chooseTags(sel, tag) // returns "[tag]sel[/tag]"
textarea[0].value = textarea[0].value.substring(0,start) + replace + textarea[0].value.substring(end,开发者_运维问答len);

And Opera and Chrome don't change scroll height. But Firefox nullifies it. How can I prevent this?

(textarea[0] is used because Opera has problem with textarea.val()'s \r deletion)


This seems to be a bug in Firefox. You can work around it by saving the current scrollTop value of the textarea and restore it after adding the tag:

var scTop = textarea[0].scrollTop,
    len = textarea[0].value.length,
    start = textarea[0].selectionStart,
    end = textarea[0].selectionEnd,
    sel = textarea[0].value.substring(start, end),
    replace = chooseTags(sel, tag); // returns "[tag]sel[/tag]"

// Add tag
textarea[0].value = textarea[0].value.substring(0,start)+
                    replace+
                    textarea[0].value.substring(end,len);
// Restore scrollTop
textarea[0].scrollTop = scTop;


You must add the following before the return sentence:

textarea[0].setSelectionRange( end + 7, end + 7 ); 
// 7 is the total length of the text tags that have been added
textarea[0].focus();

It worked for me in a modified version of your jsfiddle: http://jsfiddle.net/carlesandres/WTQMa/1/

Is this what you needed?

0

精彩评论

暂无评论...
验证码 换一张
取 消