将光标放在文本框中指定的长度

时间:2012-10-11 06:13:31

标签: javascript jquery

  

可能重复:
  Set cursor at a length of 14 onfocus of a textbox

我有一个代码,它在文本框中选择一定长度的子字符串。我想放置光标而不是选择整个字符串。代码如下

<script type="text/javascript">
window.onload = function() {
    $("#message").keyup(function(e){
        var message = document.getElementById('message');
        // Select a portion of text
        createSelection(message, 0, 5);

        // get the selected portion of text
        var selectedText = message.value.substring(message.selectionStart, message.selectionEnd);
        alert(selectedText);
    });
    function createSelection(field, start, end) {
    if( field.createTextRange ) {
        var selRange = field.createTextRange();
        selRange.collapse(true);
        selRange.moveStart('character', start);
        selRange.moveEnd('character', end-start);
        selRange.select();
    } else if( field.setSelectionRange ) {
        field.setSelectionRange(start, end);
    } else if( field.selectionStart ) {
        field.selectionStart = start;
        field.selectionEnd = end;
    }
    field.focus();
    }}

</script>

代码的HTML部分

<input type="text" name="message" id="message" value="" />

3 个答案:

答案 0 :(得分:1)

我根据this topic的答案创建了一个简单的jQuery插件函数。

$.fn.setCursorPos = function(position) {
    return this.each(function() {
        var node = this;

        node.focus();

        if (node.setSelectionRange) {
            node.setSelectionRange(position, position);
        } else if (node.createTextRange) {
            var textRange = node.createTextRange();
            textRange.collapse(true);
            textRange.move('character', position);
            textRange.select();
        }
        node.selectionStart = position;
    });
};

jsFiddle上的演示。

答案 1 :(得分:0)

您可以定义setCursor函数:

function setCursor(node,pos){

    var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;

    if(!node)
        return false;
    else if(node.createTextRange)
    {
        var textRange = node.createTextRange();

        textRange.collapse(true);
        textRange.moveEnd(pos);
        textRange.moveStart(pos);
        textRange.select();
        return true;
    }
    else if(node.setSelectionRange)
    {
        node.setSelectionRange(pos,pos);
        return true;
    }

    return false;
}

在您的脚本中使用:

field.focus(function(){
   var done = setCursor(message, 3);
   // you can check the done boolean if you want ...
});

Sources

答案 2 :(得分:0)

看到@My_Boon的想法,我改变了自己的代码。刚刚更改了两个参数,这里是新的答案。我刚刚改变了

else if( field.setSelectionRange ) {
        field.setSelectionRange(end, end);
    } else if( field.selectionStart ) {
        field.selectionStart = end;
        field.selectionEnd = end;
    }

field.setSelectionRange(end, end); this line was `field.setSelectionRange(start, end);`