HTML Input Text cursor position control


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> new document </title>
    <META NAME="Generator" CONTENT="EditPlus,Microshaoft">
    <META NAME="Author" CONTENT="EditPlus,Microshaoft">
    <META NAME="Keywords" CONTENT="EditPlus,Microshaoft">
    <META NAME="Description" CONTENT="EditPlus,Microshaoft">
    <script type="text/javascript">
    <!--
        function GetTextBoxCursorPosition(inputText) {
            var cursorPosition = 0;
            // IE
            if(document.selection) {
                inputText.focus();
                var textRange = document.selection.createRange();
                textRange.moveStart('character', - inputText.value.length);
                cursorPosition = textRange.text.length;
            }
            // Firefox
            else if(inputText.selectionStart || inputText.selectionStart == '0') {
                cursorPosition = inputText.selectionStart;
            }
            return cursorPosition;
        }
        function SetInputTextCursorPosition(inputText, cursorPosition) {
            // IE
            if(document.selection) { 
                inputText.focus();
                var textRange = document.selection.createRange();
                textRange.moveStart('character', - inputText.value.length);
                textRange.moveStart('character', cursorPosition);
                textRange.moveEnd('character', 0);
                textRange.select();
            }
            else if(inputText.selectionStart || inputText.selectionStart == '0') {
                inputText.selectionStart = cursorPosition;
                inputText.selectionEnd = cursorPosition;
                inputText.focus();
            }
        }
    //-->
    </script>
</head>
<body>
    <table border="1">
        <tr>
            <td colspan="2" align="center">
                <input type="text" id="text1" value="!@#123QWEasd" />
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" id="button1" value="Set Cursor Position" onclick="SetInputTextCursorPosition(document.getElementById('text1'), parseInt(document.getElementById('text2').value));" />
            </td>
            <td>
                <input type="text" id="text2" />
            </td>
        </tr>
    </table>
    <script type="text/javascript">
    <!--
        var x = document.getElementById("text1");
        x.onkeydown = x.onclick = x.onselect = onCursorPositionChange;
        function onCursorPositionChange()
        {
            var sender = window.event.srcElement;
            if (sender.type == "text")
            {
                document.getElementById("text2").value = GetTextBoxCursorPosition(sender);
            }
        }
    //-->
    </script>
</body>
</html>

原文地址:https://www.cnblogs.com/Microshaoft/p/2691525.html