开发者

Why does IE 8 make the cursor jump to the end of the textarea for this JS?

http://jsfiddle.net/tYXTX/

In Firefox, with the above script (included inline below), you can edit the textarea's contents at any point either by clicking in the middle of the string and typing, or using the keyboard back keys (and ctrl+left arrow).

In IE, the cursor always jumps to the end. Why is this, and how can I prevent it?


HTML:

<textarea id="bob" name="bob">Some textarea content</textarea>
<div id=开发者_如何学编程"debug"></div>

JS:

$(document).ready(function(){
    $("#bob").keyup(function(){
        $("#bob").val($("#bob").val().substring(0,160));
        $("#debug").append("\n+");
    }); 
});


Instead of truncating $("#bob") using substring() every time, do it only when the text length is greater than 160:

$(document).ready(function(){
    var oldtext = $("#bob").val();

    $("#bob").keyup(function(){
        if( $("#bob").val().length > 160 )
            $("#bob").val(oldtext);
        else
            oldtext = $("#bob").val();

        $("#debug").append("\n+");
    });
});

In IE, whenever the <textarea> gets modified, the cursor will jump to the end.


I guess IE cleans the textbox value and then inserts new text. As a result, the caret position is lost.

What you can do is saving the caret position in memory and restore it after setting the value: http://jsfiddle.net/pimvdb/tYXTX/3/.

$(document).ready(function(){
    $("#bob").keyup(function(){
        var caretPosition = $("#bob").prop("selectionStart"); // caret position

        $("#bob").val($("#bob").val().substring(0,160));

        $("#bob").prop({selectionStart: caretPosition,   // restore caret position
                        selectionEnd:   caretPosition});
        // if start == end, it defines the caret position as selection length == 0

        $("#debug").append("\n+");
    }); 
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜