在浏览器中光标当前位置插入文本
我有一个模式窗口,可以帮助格式化文本。 我的窗口上有多个文本区域。 模式不应附加到特定的文本区域,因此当我在模式窗口中按下图标时,我需要在光标当前所在的位置插入字符串/表情符号等。 我的问题是,我如何知道光标当前位于哪个元素(文本区域/输入/其他)?
I have a modal window which helps formatting text.
I have multiple textareas on the window.
The modal should not be attached to a specific textarea, so when I press an Icon in the modal window, I need to insert a string/emoticon etc where-ever the cursor is currently.
My question, How do I know in which element (textarea/input/whatever) the cursor is currently in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所有浏览器的最新版本都支持 document.activeElement。这将告诉您当前在该窗口中哪个字段具有焦点(即光标所在的位置)。然后,您需要知道如何在当前光标位置插入文本。下面的函数就是这样做的。
因此,从弹出窗口中,按钮处理程序应调用以下方法
The latest version of all browsers support document.activeElement. That will tell you which field currently has focus within that window (that's where the cursor is). Then, you'll need to know how to insert text at the current cursor position. The following function does just that.
Therefore, from your popup, your button handler should call the following method
似乎没有像
isfocused
这样的属性,您可以通过检查来确定特定文本字段是否具有焦点。不过,您可以为每个文本框的onFocus
事件创建一个事件处理程序,并让它在变量中记录新聚焦的文本框的 ID,以便您稍后检查。另外,您可能对本教程感兴趣,它告诉您如何在给定字段中的当前光标位置插入文本(一旦确定了焦点字段,例如使用上述方法)。
There doesn't seem to be a property like
isfocused
that you can just check in order to determine whether a particular text field has focus. However, you could create an event handler for theonFocus
event for each of the text boxes, and have it record ID of the newly-focused textbox in a variable so that you can check it later.Also, you may be interested in this tutorial, which tells you how to insert text at the current cursor position within a given field (once you've determined which field is focused, e.g. using the above method).