8

海伙计们,我想在一个没有值的文本框上将光标设置在长度为 14 的位置。我知道最初光标将在 0 我希望它在 14

4

3 回答 3

20

IE 在设置光标位置时使用了与 Firefox、Opera 和 Chrome 不同的方法。最好制作一个辅助函数,它会为你做这件事。我用这个来满足自己的需要。

function setCursor(node,pos){

    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;
}

最后一件事是从您的 onfocus 处理程序中调用它。

祝你好运

于 2009-12-08T14:40:27.813 回答
2

moveStart 和 moveEnd 方法需要 2 个参数。第一个参数是一个字符串(字符、单词、句子或文本编辑器)。第二个参数是一个整数,表示要移动的单位数。 http://msdn.microsoft.com/en-us/library/ie/ms536623%28v=vs.85%29.aspx

于 2012-10-30T16:59:03.757 回答
0

$("#textbox").selectionStart=14可能适用于 Firefox、Opera、Chrome,但不确定是否适用于 IE

PS:文本框中应该有长度为 14 > 的字符才能正常工作。

于 2009-12-08T08:48:19.963 回答