jQuery:在没有浏览器特定代码的情况下获取输入中文本的光标位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4085312/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:38:08  来源:igfitidea点击:

jQuery: Get the cursor position of text in input without browser specific code?

jqueryinputcursor-position

提问by Ansgar

Is there any way in jQuery to get the current cursor-position in an text input without doing ugly browser specific code?

在 jQuery 中有什么方法可以在不执行难看的浏览器特定代码的情况下获取文本输入中的当前光标位置吗?

Like in:

像:

<input id="myTextInput" type="text" value="some text" >

the cursor being after the "x" of "some text", I can get "8"?

光标在“某些文本”的“x”之后,我可以得到“8”吗?

回答by Nick Craver

You can't do this without somebrowser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.

如果没有一些浏览器特定的代码,您就无法做到这一点,因为它们实现的文本选择范围略有不同。但是,有一些插件可以将其抽象化。对于您所追求的,有jQuery Caret (jCaret) 插件

For your code to get the position you could do something like this:

为了让您的代码获得位置,您可以执行以下操作:

$("#myTextInput").bind("keydown keypress mousemove", function() {
  alert("Current position: " + $(this).caret().start);
});

You can test it here.

你可以在这里测试

回答by Daniel Gill

A warning about the Jquery Caret plugin.

关于 Jquery Caret 插件的警告。

It will conflict with the Masked Input plugin(or vice versa). Fortunately the Masked Input plugin includes a caret() function of its own, which you can use very similarly to the Caret plugin for your basic needs - $(element).caret().begin or .end

它会与Masked Input 插件冲突(反之亦然)。幸运的是,Masked Input 插件包含它自己的 caret() 函数,您可以使用它与 Caret 插件非常相似以满足您的基本需求 - $(element).caret().begin 或 .end

回答by Rajesh Paul

Using the syntax text_element.selectionStartwe can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.valueand in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd.

使用语法,text_element.selectionStart我们可以根据所选文本的第一个字符的索引来获取文本选择的起始位置,text_element.value如果我们想要获得与选择中最后一个字符相同的字符,我们必须使用text_element.selectionEnd.

Use it as follows:

使用方法如下:

<input type=text id=t1 value=abcd>
<button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>

I'm giving you the fiddle_demo

我给你fiddle_demo

回答by Chinmayee G

just came across while browsing, might help you javascript-getting-and-setting-caret-position-in-textarea. You can use it for textbox also.

刚在浏览时遇到,可能对你有帮助javascript-getting-and-setting-caret-position-in-textarea。您也可以将它用于文本框。