设置input光标位置:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="text" id="test-input" value="Example" />
<input type="text" id="test-input2" value="Example" />
</body>
<script> function setCaretPosition(ctrl, pos) { // Modern browsers if(ctrl.setSelectionRange) { ctrl.focus(); ctrl.setSelectionRange(pos, pos); // IE8 and below } else if(ctrl.createTextRange) { var range = ctrl.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } } var input = document.getElementById('test-input'); setCaretPosition(input, input.value.length); </script>
</html>
注意:不支持type为number类型的input