开发者

Possible to know the position of the text cursor in an input field

开发者 https://www.devze.com 2023-03-16 16:53 出处:网络
If a 开发者_Python百科user is typing in an input field, I know that you can focus on the element to put the cursor there, but is there a way to position the cursor in the input? say half way? thanksTr

If a 开发者_Python百科user is typing in an input field, I know that you can focus on the element to put the cursor there, but is there a way to position the cursor in the input? say half way? thanks


Try this

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;
        }

associate this function to the onkeyup, onkeydown and onmouseup and onmousedown to get the location tryit out over here

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号