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

标签 javascript

如果用户在输入字段中键入内容,我知道您可以将焦点放在元素上以将光标放在那里,但是有没有办法将光标定位在输入中?说一半?谢谢

最佳答案

试试这个

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 以获取位置 tryit over here

关于javascript - 可以知道文本光标在输入字段中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6554093/

相关文章:

javascript - fullcalendar 不允许我调整事件的大小(光标不显示,我做错了)

javascript - 当存在基本 href 时,通过更新 location.path 来更改 UI 路由器状态

javascript - jquery 点击 .addClass 问题

javascript - 给定偏移量,使用 javascript 将跨度添加到文本字符串

php - xmlHttp 字符串传递

javascript - 背景轮播在幻灯片图像中包含 DIV

javascript - 在 JavaScript 中传递数组值

javascript - c3.js - 如何将 y 行值设置为 url 中的第一个值(json 数据)

javascript - 使用 webos Enyo 应用程序加载速度更快

javascript - 如何在 Opera/Google Chrome 浏览器中打开两个选项卡窗口?