我想做一个自动完成,如果一个人输入一个“@”,他们会得到一个自动完成的名字列表。
我正在使用 jQueryUI 自动完成,我的解决方案(http://jsfiddle.net/aUfrz/22/)的唯一问题是需要将可自动完成的文本输入放置在 textarea 光标位置而不是就目前而言。
这是我在 JSFiddle 中的 JS:
$(document.body).on('keypress', 'textarea', function(e) {
   var names = [
        "johnny",
        "susie",
        "bobby",
        "seth"
    ],
    $this=$(this),
    char = String.fromCharCode(e.which);
    if(char == '@') {
       console.log('@ sign pressed');
       var input=$('<input style="position:relative; top:0px; left:0px;background:none;border:1px solid red" id="atSign" >');
       $this.parent().append(input);
       input.focus();
       input.autocomplete({
        source: names,
        select: function (event, ui) {
            console.log('value selected'+ui.item.value);
            //$this.val('@'+ui.item.value);
            $this.insertAtCaret(ui.item.value);
            $this.focus();
            input.remove();
        } //select
    });  //autocomplete
  } //if 
}); // keypress
HTML:
<textarea></textarea>
请注意,我没有在此处显示用于在插入符号位置插入所选自动完成建议的 jQuery 插件:insertAtCaret()我在 this other SO question中找到的。

