可以知道文本光标在输入字段中的位置

时间:2011-07-01 23:20:33

标签: javascript

如果用户在输入字段中输入,我知道您可以专注于元素以将光标放在那里,但有没有办法将光标定位在输入中?说半路?感谢

1 个答案:

答案 0 :(得分:1)

试试这个

function GetCursorLocation(CurrentTextBox)
        {
            var CurrentSelection, FullRange, SelectedRange, LocationIndex = -1;
            if (typeof CurrentTextBox.selectionStart == "number")
            {
                LocationIndex = CurrentTextBox.selectionStart;
            }
            else if (document.selection && CurrentTextBox.createTextRange)
            {
                CurrentSelection = document.selection;
                if (CurrentSelection)
                {
                    SelectedRange = CurrentSelection.createRange();
                    FullRange = CurrentTextBox.createTextRange();
                    FullRange.setEndPoint("EndToStart", SelectedRange);
                    LocationIndex = FullRange.text.length;
                }
            }
            return LocationIndex;
        }

将此函数与onkeyup,onkeydown和onmouseup以及onmousedown关联,以获取here上的位置tryit