我正在尝试实现标记,就像 facebook 对 @friendname 所做的那样。我有一个文本区域,我想检测用户何时输入@。如何使用 keyup 监听器执行此操作?是否可以使用 keyup 获取输入的文本?这就是我现在拥有的
$("#recommendTextArea").keyup(function () {
var content = $(this).val(); //content Box Data
var go = content.match(start); //content Matching @
var name = content.match(word); //content Matching @friendname
console.log(content[content.length-1]);
//If @ available
if(go.length > 0)
{
//if @abc avalable
if(name.length > 0)
{
//do something here
}
}
});
最重要的是我需要的是用户刚刚输入的“@”的索引。
最佳答案
(function ($, undefined) {
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
$("#recommendTextArea").on('keypress', function(e){
var key = String.fromCharCode(e.which);
if(key === '*') {
var position = $(this).getCursorPosition();
alert(position); // It is the position
alert($(this).val()); // This is the value
}
});
我做了一些更改HERE .
关于javascript - 在文本区域中键入后检测光标之前的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16564259/