开发者

Create an autocompleter like the Facebook status update

开发者 https://www.devze.com 2023-01-02 04:13 出处:网络
I\'m trying to create a div with contenteditable like the Facebook status update. Then I mean I want to show an autocomplete box when the user have written @.

I'm trying to create a div with contenteditable like the Facebook status update. Then I mean I want to show an autocomplete box when the user have written @.

How would you do that. Currently I'm just playing with keypress and check if the keycode = 64. Somehow that works, but it doesn't validate开发者_如何学Python if there's a space before the alfa, or if the user has unfocused the box, then focused it again.

Any ideas? Or do you know about any plugin that works something like that?

Tnx


I'd probably do it with keypress too.

but we need to check the cursor position to check the character before the '@'.

here's the function I used from http://javascript.nwbox.com/cursor_position/cursor.js

function getSelectionStart(o) {
  if (o.createTextRange) {
    var r = document.selection.createRange().duplicate();
    r.moveEnd('character', o.value.length); 
    if (r.text == '') return o.value.length
      return o.value.lastIndexOf(r.text);
    } else { 
      return o.selectionStart;
    }
}

then with jquery I wrote this keypress callback function:

txt.keypress(function(event) {
    if (event.which == 64) {
        var index = getSelectionStart(this)
        var prevChar = txt.val().substring(index - 1, index);
        // now you can check if the previous char was a space
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消