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

回眸只為那壹抹淺笑 提交于 2019-12-05 02:05:24

问题


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+");
    }); 
});

回答1:


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.




回答2:


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+");
    }); 
});


来源:https://stackoverflow.com/questions/6899047/why-does-ie-8-make-the-cursor-jump-to-the-end-of-the-textarea-for-this-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!