0

jquery获取(设置)文本框(块)内光标位置插件

Posted by 晴云孤魂 on 2011 年 07 月 27 日 in web development |

/**
* @author 全冠清
*/
$.fn.extend({
position:function( value ){
var elem = this[0];
if (elem&&(elem.tagName=="TEXTAREA"||elem.type.toLowerCase()=="text")) {
if($.browser.msie){
var rng;
if(elem.tagName == "TEXTAREA"){
rng = event.srcElement.createTextRange();
rng.moveToPoint(event.x,event.y);
}else{
rng = document.selection.createRange();
}
if( value === undefined ){
rng.moveStart("character",-event.srcElement.value.length);
return rng.text.length;
}else if(typeof value === "number" ){
var index=this.position();
index>value?( rng.moveEnd("character",value-index)):(rng.moveStart("character",value-index))
rng.select();
}
}else{
if( value === undefined ){
return elem.selectionStart;
}else if(typeof value === "number" ){
elem.selectionEnd = value;
elem.selectionStart = value;
}
}
}else{
if( value === undefined )
return undefined;
}
}
})

HTML代码:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
  <title>测试</title>
 </head>
 <script language="JavaScript" type="text/javascript" src="jquery-1.3.1.min.js"></script>
 <script language="JavaScript" type="text/javascript" src="jquery-position.js"></script>
 <script language="JavaScript" type="text/javascript">
  $(document).ready(function(){
   $('input:eq(0)').click(function(){
    alert($(this).position());
   })
   $('input:eq(1)').click(function(){
    $(this).position(4);
   })
  })
 </script>
 <body>
  <input type="text"  value="123456789"/>
  <input type="text"  value="123456789"/>
 </body>
</html>

JS代码

    $.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();
                }
        });
    };

Copyright © 2011-2021 晴云孤魂's Blog All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.

普人特福的博客cnzz&51la for wordpress,cnzz for wordpress,51la for wordpress