JS-设置input光标位置

设置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

    原文作者:半笙彷徨
    原文地址: https://blog.csdn.net/wang704987562/article/details/82560869
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞