jquery 光标位置
以下是一些代码片段以及有关如何使用jQuery&HTML5设置光标Input Focus和Cursor Positions的示例,这些是登录表单等常用的操作。 欢迎提出意见,改进和建议。
jQuery输入焦点
只需调用focus()函数即可将焦点设置为输入。
//set focus on input
$('input[name=firstName]').focus();
HTML5输入焦点
HTML5提供的强大功能…在http://html5please.com/上找不到此功能,但是我已经测试了它在Chrome和Firefox中可以正常运行,但在IE9或更低版本中却无法正常工作。
//AUTO INPUT FOCUS
<input type="text" name="myInput" autofocus />
jQuery设置光标位置
jQuery函数可将光标位置设置为输入字段中特定字符的位置。
//SET CURSOR POSITION
$.fn.setCursorPosition = function(pos) {
this.each(function(index, elem) {
if (elem.setSelectionRange) {
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
});
return this;
};
用法示例
设置第一个字符后的光标位置。
$('#username').setCursorPosition(1);
jQuery设置光标位置
jQuery函数可在输入字段中自动选择文本(特定数目的字符)。
//SELECT TEXT RANGE
$.fn.selectRange = function(start, end) {
return this.each(function() {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
用法示例
选择输入中的前5个字符。
$('#username').selectRange(0,5);
翻译自: https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/
jquery 光标位置