【问题标题】:Why does IE 8 make the cursor jump to the end of the textarea for this JS?为什么 IE 8 让光标跳到这个 JS 的文本区域的末尾?
【发布时间】:2011-10-17 11:05:48
【问题描述】:

http://jsfiddle.net/tYXTX/

在 Firefox 中,使用上面的脚本(包括在下面的内联脚本),您可以通过单击字符串中间并键入,或使用键盘返回键(和 ctrl+左箭头)随时编辑 textarea 的内容.

在 IE 中,光标总是跳到末尾。为什么会这样,我该如何预防?


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

【问题讨论】:

    标签: javascript internet-explorer textarea text-cursor


    【解决方案1】:

    不要每次都使用substring()截断$("#bob"),而是仅在文本长度大于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+");
        });
    });
    

    在IE中,每当&lt;textarea&gt;被修改时,光标都会跳到末尾。

    【讨论】:

      【解决方案2】:

      我猜 IE 会清理文本框的值,然后插入新文本。结果,插入符号位置丢失。

      您可以做的是将插入符号位置保存在内存中,并在设置值后恢复它: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+");
          }); 
      });
      

      【讨论】:

        猜你喜欢
        • 2011-08-17
        • 2012-04-26
        • 1970-01-01
        • 2020-02-21
        • 1970-01-01
        • 2020-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多