简体   繁体   中英

How to set cursor position in text input in Safari

I want to set position for cursor in input field with id="get" to a specified value in another input field with id="no". It works when I enter value to input field with id="no" but it doesn't work (in safari only) when I enter value to input field with id="get". In IE/Firefox/Opera it all works. Masters, what is the reason?? This is my code:

<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">

I can't test in Safari at the moment, but I think anyway it is better to bind to some onblur or focusout event. At the moment you are trying to set caret position when editing the second field.

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

Demo: http://jsfiddle.net/beshur/uFaFt/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM