2013-10-25 154 views
1

我想在id =「get」的輸入字段中將光標的位置設置爲ID =「no」的另一個輸入字段中的指定值。當我爲id =「no」的輸入字段輸入值時工作,但它在id =「get」的輸入字段中輸入值時不起作用(僅限safari)。在IE/Firefox/Opera中一切正常。大師賽是什麼原因? 這是我的代碼:如何在Safari中的文本輸入中設置光標位置

<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

在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/

相關問題