简体   繁体   English

如何使用javascript在插入符号位置键入文本?

[英]How to type text at the caret position using javascript?

I am making a special character menu for an input. 我正在为输入制作特殊字符菜单。 when they click on an options menu, the app must paste the special character at the placement of the caret(the mouse cursor). 当他们单击选项菜单时,应用程序必须将特殊字符粘贴在插入符号(鼠标光标)的位置。

It also seems to reset the caret's position at the end of the text box whenever the code edits the input with document.getElementById("id").value , any way to fix that? 每当代码使用document.getElementById("id").value编辑输入时,似乎也可以重置插入符号在文本框末尾的位置,有什么办法可以解决?

Sorry if this was asked before, i did a bunch of research and did not find anything. 抱歉,如果之前有人问过我,我做了很多研究,没有发现任何东西。

First of all you need to store the caret position so that even when the input doesn't have focus you know it's last position. 首先,您需要存储插入符号的位置,以便即使输入没有焦点,您也知道它的最后位置。 You can do this by listening to a range of events that may mean the caret position has changed. 您可以通过侦听一系列可能意味着插入符号位置发生变化的事件来执行此操作。

Then when the user clicks the button to add a special character, you can place the special character at the caret position you stored. 然后,当用户单击按钮以添加特殊字符时,可以将特殊字符放在存储的插入符号位置。 You can also return focus, setting the caret back to it's last position. 您还可以返回焦点,将插入符号设置回其最后位置。

I've found a great example of how to keep track of the caret position: Cursor Position Control Example 我找到了一个很好的示例来跟踪插入符号的位置: 光标位置控制示例

Hopefully this will get you going in the right direction. 希望这将使您朝正确的方向前进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM