简体   繁体   English

如何使textarea可编辑?

[英]How to make textarea editable?

I have a textarea which converts English to Hindi onkeyup event. 我有一个textarea ,可将英语转换为印地语onkeyup事件。 But when I move the caret backward for editing, the first letter I type converts to Hindi and the caret moves to the end of the string. 但是,当我将插入符号向后移动以进行编辑时,我键入的第一个字母将转换为北印度语,而插入符号将移动到字符串的末尾。 Is possible to store the caret at the same point within the textarea , so that it doesn't move to the end of the string? 是否可以将插入号存储在textarea中的同一点,以使其不会移动到字符串的末尾?

The issue with this is that you are overwriting the value of the textarea every key up which is what makes the caret move. 这样做的问题是,每按一次键,您都将覆盖textarea的值,这就是使插入符号移动的原因。

You will want to get the value of the caret before you replace the text and set it again after the replace. 替换文本之前,您将需要获得插入符号的值,并替换后再次设置它。

Stackoverflow Answer: Get Caret Position - Code from linked answer below unaltered Stackoverflow答案:获得插入位置 -以下链接答案中的代码未更改

function getCaret(el) { 
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
        rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    return rc.text.length; 
  }  
  return 0; 
}

Stackoverflow Answer: Set Caret Position - Code from linked answer below unaltered Stackoverflow答案:设置插入符位置 -以下链接答案中的代码未更改

function SetCursorPosition(pos)
{
    // HERE txt is the text field name
    var obj=document.getElementById('<%= txt.ClientID %><%= txt.ClientID %>');

    //FOR IE
    if(obj.setSelectionRange)
    {
        obj.focus();
        obj.setSelectionRange(pos,pos);
    }

    // For Firefox
    else if (obj.createTextRange)
    {
        var range = obj.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

There are a few other methods to get around this by avoiding the replacing all the text on a key up event and move it to a button press, blur/unfocus or something else. 通过避免替换按键事件中的所有文本并将其移至按下按钮,模糊/散焦或其他某种方式,还有其他一些方法可以解决此问题。 This allows you not to worry about any caret position resetting to the end. 这使您不必担心插入符位置重置到最后的担心。

The only real disadvantage I see for moving to another event to trigger text change is simply that it is not instantaneous. 我看到移到另一个事件以触发文本更改的唯一真正的缺点就是它不是瞬时的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM