如果用户在输入字段中键入内容,我知道您可以将焦点放在元素上以将光标放在那里,但是有没有办法将光标定位在输入中?说一半?谢谢
最佳答案
试试这个
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/