输入文字选择代码段

只需构建输入选择代码段的集合即可。 Chrome和Firefox的最新版本使用.setSelectionRange()函数。 别忘了Firefox在设置范围之前需要首先关注一个元素。 请参见Input.setSelectionRange

相关文章: HTML5输入自动对焦

获取光标位置

// GET CURSOR POSITION
jQuery.fn.getCursorPosition = function(){
    if(this.lengh == 0) return -1;
    return $(this).getSelectionStart();
}

设置文字选择

jQuery.fn.getSelectionStart = function(){
    if(this.lengh == 0) return -1;
    input = this[0];

    var pos = input.value.length;

    if (input.createTextRange) {
        var r = document.selection.createRange().duplicate();
        r.moveEnd('character', input.value.length);
        if (r.text == '')
        pos = input.value.length;
        pos = input.value.lastIndexOf(r.text);
    } else if(typeof(input.selectionStart)!="undefined")
    pos = input.selectionStart;

    return pos;
}

设置光标位置

//SET CURSOR POSITION
jQuery.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;
};

设置光标位置(v2)

//different version of SET CURSOR POSITION function above
function setCursorPos(node,pos){

    var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
    node.focus(); //crucial for firefox

    if(!node){
        return false;
    }else if(node.createTextRange){
        var textRange = node.createTextRange();
        textRange.collapse(true);
        // textRange.moveEnd(pos); //see api textRange requires 2 params
        // textRange.moveStart(pos);
        textRange.moveStart('character', pos);
        textRange.moveEnd('character', 0);
        // console.log('textRange...');
        textRange.select();
        return true;
    }else if(node.setSelectionRange){
        node.setSelectionRange(pos,pos);
        // console.log('setSelectionRange...');
        return true;
    }

    return false;
}

From: https://www.sitepoint.com/input-text-selection-code-snippets/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值