在文本框中插入@對象

1、在文本框中插入@對象javascript

var name = li.children("input[type=checkbox]").attr("data-name");
var textarea = li.parents(".comment-form").find(".comment-box textarea");
var content = textarea.val();
if (content.indexOf(name) < 0) {
    var startPos = textarea[0].selectionStart,//光標所選範圍的起始位置
    endPos = textarea[0].selectionEnd,//光標所選範圍的結束位置
    cursorPos = startPos,//當前焦點位置=起始位置
    content = content.substring(0, startPos) + " @" + name + " " 
      + content.substring(endPos, content.length);
    cursorPos = content.length; //當前焦點位置=文字尾部位置
    textarea[0].selectionStart = textarea[0].selectionEnd = cursorPos;
    textarea.val(content);
}

2、在文本框中插入@對象(包含在文本中輸入name部分文字後自動搜索彈出選項插入name所有文字)java

var name = li.children("input[type=checkbox]").attr("data-name");
var textarea = li.parents(".comment-form").find(".comment-box textarea");
var content = textarea.val();

var startPos = textarea[0].selectionStart,//光標所選範圍的起始位置
endPos = textarea[0].selectionEnd,//光標所選範圍的結束位置
cursorPos = startPos;//當前焦點位置=起始位置

var content2 = content.substring(0, startPos);
var start = content2.lastIndexOf("@");
if (content2.length - start > 1 && startPos >= start && start >= 0) {
    var key = content2.substring(start + 1, content2.length);
    console.log(name.indexOf(key));
    if (name.indexOf(key) >= 0) content = content.substring(0, start - 1) + " @" + name + " "
        + content.substring(endPos, content.length);
    else content = content.substring(0, startPos) + " @" + name + " " 
        + content.substring(endPos, content.length);
} else content = content.substring(0, startPos) + " @" + name + " " 
    + content.substring(endPos, content.length);
cursorPos = endPos; //當前焦點位置=文字尾部位置
textarea[0].selectionStart = textarea[0].selectionEnd = cursorPos;
textarea.val(content);
相關文章
相關標籤/搜索