2010-09-02 46 views
2

在文本区域如何插入模式name下一个使用jQuery和后光标应该是该模式之后光标位置:这应该在按钮上发生点击jQuery的文字区域 - 插入模式光标位置

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

回答

2

请参阅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> 

希望这有助于!

+0

谢谢,我会从这里弄明白.. – Rajeev 2010-09-02 13:49:11