【问题标题】:jQuery textarea - insert pattern cursor positionjQuery textarea - 插入模式光标位置
【发布时间】:2011-04-07 06:31:20
【问题描述】:

如何在文本区域中使用 jQuery 在光标位置旁边插入模式name,然后光标应该在模式之后:这应该发生在按钮单击时

     <input type="button" value="insert pattern" >
     <textarea rows="10" id="comments">INSERT The condition</textarea>

【问题讨论】:

    标签: jquery jquery-plugins jquery-selectors jquery-validate


    【解决方案1】:

    请参阅this answer。这就是我得到 insertAtCaret() 方法的地方。我继续将它连接到您的按钮...不确定您所说的“模式name”到底是什么意思。那是SQL的事情吗?它是否基于 HTML 中的某些先前输入字段?如果没有更多细节,很难提供更多帮助。

    function insertAtCaret(areaId,text) {
        var txtarea = document.getElementById(areaId);
        var scrollPos = txtarea.scrollTop;
        var strPos = 0;
        var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
            "ff" : (document.selection ? "ie" : false ) );
        if (br == "ie") { 
            txtarea.focus();
            var range = document.selection.createRange();
            range.moveStart ('character', -txtarea.value.length);
            strPos = range.text.length;
        }
        else if (br == "ff") strPos = txtarea.selectionStart;
    
        var front = (txtarea.value).substring(0,strPos);  
        var back = (txtarea.value).substring(strPos,txtarea.value.length); 
        txtarea.value=front+text+back;
        strPos = strPos + text.length;
        if (br == "ie") { 
            txtarea.focus();
            var range = document.selection.createRange();
            range.moveStart ('character', -txtarea.value.length);
            range.moveStart ('character', strPos);
            range.moveEnd ('character', 0);
            range.select();
        }
        else if (br == "ff") {
            txtarea.selectionStart = strPos;
            txtarea.selectionEnd = strPos;
            txtarea.focus();
        }
        txtarea.scrollTop = scrollPos;
    }
    
    
    $(document).ready(function(){
      $("#insertPattern").click(function(){
        insertAtCaret("comments","name");
      });
    });​
    

    然后,在您的 HTML 中:

      <input id="insertPattern" type="button" value="insert pattern" />
      <textarea rows="10" id="comments">INSERT The condition</textarea>
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 2011-08-10
      • 2010-11-07
      • 2012-04-30
      相关资源
      最近更新 更多