Javascript 获取文本输入字段中的光标位置(以字符为单位)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2897155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get cursor position (in characters) within a text Input field
提问by MarkB29
How can I get the caret position from within an input field?
如何从输入字段中获取插入符号位置?
I have found a few bits and pieces via Google, but nothing bullet proof.
我通过谷歌找到了一些零碎的东西,但没有防弹。
Basically something like a jQuery plugin would be ideal, so I could simply do
基本上像 jQuery 插件这样的东西是理想的,所以我可以简单地做
$("#myinput").caretPosition()
回答by bezmax
Easier update:
更简单的更新:
Use field.selectionStartexample in this answer.
field.selectionStart在此答案中使用示例。
Thanks to @commonSenseCode for pointing this out.
感谢@commonSenseCode 指出这一点。
Old answer:
旧答案:
Found this solution. Not jquery based but there is no problem to integrate it to jquery:
找到了这个解决方案。不是基于 jquery,但将其集成到 jquery 没有问题:
/*
** Returns the caret (cursor) position of the specified text field (oField).
** Return value range is 0-oField.value.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange();
// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;
// Return results
return iCaretPos;
}
回答by MarkB29
Nice one, big thanks to Max.
不错,非常感谢 Max。
I've wrapped the functionality in his answer into jQuery if anyone wants to use it.
如果有人想使用它,我已经将他的答案中的功能包装到 jQuery 中。
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
回答by CommonSenseCode
VERY EASY
好简单
Updated answer
更新答案
Use selectionStart, it is compatible with all major browsers.
使用上selectionStart,它兼容所有主流浏览器。
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
<input id="foobar" />
Update: This works only when no type is defined or type="text"on the input.
更新:这仅在未定义类型或type="text"输入时有效。
回答by Rajesh Paul
Got a very simple solution. Try the following code with verified result-
得到了一个非常简单的解决方案。尝试使用以下代码验证结果-
<html>
<head>
<script>
function f1(el) {
var val = el.value;
alert(val.slice(0, el.selectionStart).length);
}
</script>
</head>
<body>
<input type=text id=t1 value=abcd>
<button onclick="f1(document.getElementById('t1'))">check position</button>
</body>
</html>
I'm giving you the fiddle_demo
我给你fiddle_demo
回答by Jens Mikkelsen
There is now a nice plugin for this: The Caret Plugin
现在有一个很好的插件:The Caret Plugin
Then you can get the position using $("#myTextBox").caret()or set it via $("#myTextBox").caret(position)
然后您可以使用$("#myTextBox").caret()或通过设置获取位置$("#myTextBox").caret(position)
回答by George
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if (document.selection) {
// IE
input.focus();
}
return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
}
})(jQuery);
回答by pmrotule
There are a few good answers posted here, but I think you can simplify your code and skip the check for inputElement.selectionStartsupport: it is not supported only on IE8 and earlier (see documentation) which represents less than 1% of the current browser usage.
这里发布了一些不错的答案,但我认为您可以简化代码并跳过inputElement.selectionStart支持检查:它仅在 IE8 及更早版本上不受支持(请参阅文档),它仅占当前浏览器使用量的不到 1% 。
var input = document.getElementById('myinput'); // or $('#myinput')[0]
var caretPos = input.selectionStart;
// and if you want to know if there is a selection or not inside your input:
if (input.selectionStart != input.selectionEnd)
{
var selectionValue =
input.value.substring(input.selectionStart, input.selectionEnd);
}
回答by dhaupin
Perhaps you need a selected range in addition to cursor position. Here is a simple function, you don't even need jQuery:
也许除了光标位置之外,您还需要一个选定的范围。这是一个简单的函数,您甚至不需要 jQuery:
function caretPosition(input) {
var start = input[0].selectionStart,
end = input[0].selectionEnd,
diff = end - start;
if (start >= 0 && start == end) {
// do cursor position actions, example:
console.log('Cursor Position: ' + start);
} else if (start >= 0) {
// do ranged select actions, example:
console.log('Cursor Position: ' + start + ' to ' + end + ' (' + diff + ' selected chars)');
}
}
Let's say you wanna call it on an input whenever it changes or mouse moves cursor position (in this case we are using jQuery .on()). For performance reasons, it may be a good idea to add setTimeout()or something like Underscores _debounce()if events are pouring in:
假设您想在输入更改或鼠标移动光标位置时调用它(在本例中,我们使用的是 jQuery .on())。出于性能原因,如果事件涌入,添加setTimeout()下划线或类似下划线的内容可能是个好主意_debounce():
$('input[type="text"]').on('keyup mouseup mouseleave', function() {
caretPosition($(this));
});
Here is a fiddle if you wanna try it out: https://jsfiddle.net/Dhaupin/91189tq7/
如果您想尝试一下,这里有一个小提琴:https: //jsfiddle.net/Dhaupin/91189tq7/
回答by Omar bakhsh
const inpT = document.getElementById("text-box");
const inpC = document.getElementById("text-box-content");
// swch gets inputs .
var swch;
// swch if corsur is active in inputs defaulte is false .
var isSelect = false;
var crnselect;
// on focus
function setSwitch(e) {
swch = e;
isSelect = true;
console.log("set Switch: " + isSelect);
}
// on click ev
function setEmoji() {
if (isSelect) {
console.log("emoji added :)");
swch.value += ":)";
swch.setSelectionRange(2,2 );
isSelect = true;
}
}
// on not selected on input .
function onout() {
// ?????? ??? ?? ??
crnselect = inpC.selectionStart;
// return input select not active after 200 ms .
var len = swch.value.length;
setTimeout(() => {
(len == swch.value.length)? isSelect = false:isSelect = true;
}, 200);
}
<h1> Try it !</h1>
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box-content" size="20" value="content">
<button onclick="setEmoji()">emogi :) </button>

