jquery 光标位置_jQuery / HTML5输入焦点和光标位置

jquery 光标位置

以下是一些代码片段以及有关如何使用jQuery&HTML5设置光标Input Focus和Cursor Positions的示例,这些是登录表单等常用的操作。 欢迎提出意见,改进和建议。

光标焦点

jQuery输入焦点

只需调用focus()函数即可将焦点设置为输入。

//set focus on input
$('input[name=firstName]').focus();

jsfiddle.net/z9Ldt/

HTML5输入焦点

HTML5提供的强大功能…在http://html5please.com/上找不到此功能,但是我已经测试了它在Chrome和Firefox中可以正常运行,但在IE9或更低版本中却无法正常工作。

//AUTO INPUT FOCUS
<input type="text" name="myInput" autofocus />

jsfiddle.net/89PHL/

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);

jsfiddle.net/tAZSs/

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);

jsfiddle.net/yMUx5/

翻译自: https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/

jquery 光标位置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值