【发布时间】:2012-09-29 11:49:22
【问题描述】:
如果我在 html textarea 控件的任何位置键入 *,我需要获取 keyup 事件的当前位置,例如 "Welcome* to jQuery"。所以我在欢迎之后有 * 意味着在第 8 位。让我知道是否有人可以帮助我。
【问题讨论】:
如果我在 html textarea 控件的任何位置键入 *,我需要获取 keyup 事件的当前位置,例如 "Welcome* to jQuery"。所以我在欢迎之后有 * 意味着在第 8 位。让我知道是否有人可以帮助我。
【问题讨论】:
这会奏效。 (注意:带引号的是 8 点,否则是 7 点)
$("#tf").on('keyup', function(){
console.log($(this).val().indexOf('*'));
});
http://jsfiddle.net/Vandeplas/hc6ZH/
更新: 具有多个 * 的解决方案
$("#tf").on('keyup', function(){
var pos = [],
lastOc = 0,
p = $(this).val().indexOf('*',lastOc);
while( p !== -1){
pos.push(p);
lastOc = p +1;
p = $(this).val().indexOf('*',lastOc);
}
console.log(pos);
});
http://jsfiddle.net/Vandeplas/hc6ZH/1/
更新:只给出您刚刚输入的 * 字符的位置
(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);
$("#tf").on('keypress', function(e){
var key = String.fromCharCode(e.which);
if(key === '*') {
var position = $(this).getCursorPosition();
console.log(position);
} else {
return false;
}
});
【讨论】:
*?这个jsfiddle.net/esDTj怎么样
以下链接帮助我使用 jQuery 本身解决了这个问题。
Cursor position in a textarea (character index, not x/y coordinates)
感谢你们的努力。
【讨论】: