设置输入框的光标置于文字末尾

    我们在项目开发过程中,会遇到这么一个问题:页面有个搜索框,点击搜索按钮或者回车键搜索后,文本框的光标置于文字前方,不便于继续输入,

影响操作,我们需要将光标置于文本之后,这时我就需要下面这段代码来控制光标。

 

为了方便使用已封闭成函数

 1 function setCursorPos( input )
 2 {
 3    var isIE = ( navigator.appName == "Microsoft Internet Explorer" );//判读是否为ie浏览器       
 4    var count = input.value.length;
 5    if(isIE){//IE
 6        var f = input.createTextRange(); //创建文本范围对象
 7        f.moveStart('character',count);  //更改范围起始位置, 如果count改为0就把光标放在text中的字符的最前面
 8        f.collapse(true);  //将插入点移动到当前范围的开始或结尾。
 9        f.select();  //将当前选中区置为当前对象,执行
10    }else{//FireFox
11        input.setSelectionRange(count,count);
12    }
13    
14    input.focus();
15 }

 

演示示例:

 1 <body>
 2 
 3 <textarea id="keyword"></textarea>
 4 <input type="button" id="btn" value="确定" />
 5 
 6 <script type="text/javascript">
 7 
 8 var btn = document.getElementById("btn");
 9 btn.onclick = function()
10 {
11      var input = document.getElementById("keyword");
12      setCursorPos( input );    
13 }
14 
15 
16 function setCursorPos( input )
17 {
18    var isIE = ( navigator.appName == "Microsoft Internet Explorer" );//判读是否为ie浏览器       
19    var count = input.value.length;
20    if(isIE){//IE
21        var f = input.createTextRange(); //创建文本范围对象
22        f.moveStart('character',count);  //更改范围起始位置, 如果count改为0就把光标放在text中的字符的最前面
23        f.collapse(true);  //将插入点移动到当前范围的开始或结尾。
24        f.select();  //将当前选中区置为当前对象,执行
25    }else{//FireFox
26        input.setSelectionRange(count,count);
27    }
28    
29    input.focus();
30 }
31 
32 
33 </script>
34 </body>
View Code

 

转载于:https://www.cnblogs.com/chengyanfen/p/3878747.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值