jQuery设置聚焦并使光标位置在文字最后

遇到一个问题:表单输入框设置了文字,然后使用jQuery的焦点停留设置办法focus()进行处理。结果发现光标位置在firefox下停留的位置不对——停留在文字的最前边!

只有IE浏览器下是正常的。这样的话肯定是不行的,于是想办法进行处理。

代码有很多种,下面给出:

方法一:

[javascript] view plain copy
print ?
  1. function setSelectionRange(input, selectionStart, selectionEnd) {  
  2.   if (input.setSelectionRange) {  
  3.     input.focus();  
  4.     input.setSelectionRange(selectionStart, selectionEnd);  
  5.   }  
  6.   else if (input.createTextRange) {  
  7.     var range = input.createTextRange();  
  8.     range.collapse(true);  
  9.     range.moveEnd(’character’, selectionEnd);  
  10.     range.moveStart(’character’, selectionStart);  
  11.     range.select();  
  12.   }  
  13. }  
  14.   
  15. function setCaretToPos (input, pos) {  
  16.   setSelectionRange(input, pos, pos);  
  17. }  

调用办法:setCaretToPos(document.getElementById("YOURINPUT"), 4);

方法二:

[javascript] view plain copy
print ?
  1. $.fn.selectRange = function(start, end) {  
  2.     return this.each(function() {  
  3.         if (this.setSelectionRange) {  
  4.             this.focus();  
  5.             this.setSelectionRange(start, end);  
  6.         } else if (this.createTextRange) {  
  7.             var range = this.createTextRange();  
  8.             range.collapse(true);  
  9.             range.moveEnd(’character’, end);  
  10.             range.moveStart(’character’, start);  
  11.             range.select();  
  12.         }  
  13.     });  
  14. };  

调用办法:$('#elem').selectRange(3,5);

方法三:

[javascript] view plain copy
print ?
  1. $.fn.setCursorPosition = function (position){  
  2. if(this.lengh == 0) return this;  
  3.     return $(this).setSelection(position, position);  
  4. }  
  5. $.fn.setSelection = function(selectionStart, selectionEnd) {  
  6.     if(this.lengh == 0) return this;  
  7.     input = this[0];  
  8.   
  9.     if (input.createTextRange) {  
  10.         var range = input.createTextRange();  
  11.          range.collapse(true);  
  12.         range.moveEnd(’character’, selectionEnd);  
  13.         range.moveStart(’character’, selectionStart);  
  14.         range.select();  
  15.     } else if (input.setSelectionRange) {  
  16.         input.focus();  
  17.         input.setSelectionRange(selectionStart, selectionEnd);  
  18.     }  
  19.   
  20.     return this;  
  21. }  
  22.   
  23. $.fn.focusEnd = function(){  
  24.     this.setCursorPosition(this.val().length);  
  25. }  
调用办法:$(element).focusEnd();

原文来自代码云。原文地址:http://codeyun.com/javascript/133.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值