如何在Safari中的文本输入中设置光标位置

时间:2013-10-25 18:38:27

标签: javascript safari

我想在id =“get”的输入字段中将光标的位置设置为id =“no”的另一个输入字段中的指定值。当我输入值为id =“no”的输入字段时它起作用但是当我输入id为“get”的输入字段的值时它不起作用(仅限于safari)。在IE / Firefox / Opera中,一切正常。大师,是什么原因? 这是我的代码:

<script>
function setCaretPosition(ctrl, pos) {
    if(ctrl.setSelectionRange) {
        setTimeout(function(){ctrl.focus();},1);
        ctrl.setSelectionRange(pos,pos);
    }
}
function process1() {
    var no = document.getElementById('no').value;
    setCaretPosition(document.getElementById('get'), no);
}
function process2(v) {
    var no = document.getElementById('no').value;
    setCaretPosition(v, no);
    //setCaretPosition(document.getElementById('get'), no);
}
</script>       
<input size="150" id="get" oninput="process2(this);" value="Please write some integer in the textbox given below and press Set Position button." /><br>
Enter Caret Position: <input oninput='process1();' value="3" id="no" size="1" type="text">

1 个答案:

答案 0 :(得分:1)

目前我无法在Safari中测试,但我认为无论如何最好绑定一些onblur或focusout事件。目前,您在编辑第二个字段时尝试设置插入位置。

onblur='g.process3("get");'

g.process3 = function(v) {

    var no = document.getElementById('no').value;
    var el = document.getElementById(v);
    el.focus();
    g.setCaretPosition(document.getElementById(v), no);
}

演示:http://jsfiddle.net/beshur/uFaFt/

相关问题