Javascript 在浏览器中光标的当前位置插入文本
我有一个模式窗口,可以帮助格式化文本。 我在窗口上有多个文本区域。 模态不应附加到特定的文本区域,因此当我在模态窗口中按下图标时,我需要在光标当前所在的位置插入字符串/表情符号等。Javascript 在浏览器中光标的当前位置插入文本,javascript,text-manipulation,Javascript,Text Manipulation,我有一个模式窗口,可以帮助格式化文本。 我在窗口上有多个文本区域。 模态不应附加到特定的文本区域,因此当我在模态窗口中按下图标时,我需要在光标当前所在的位置插入字符串/表情符号等。 我的问题是,我如何知道光标当前位于哪个元素(textarea/input/where)中?似乎没有类似于isfocused的属性,您可以通过检查来确定特定文本字段是否具有焦点。但是,您可以为每个文本框的onFocus事件创建一个事件处理程序,并让它在一个变量中记录新聚焦文本框的ID,以便稍后检查 此外,您可能会对以下
我的问题是,我如何知道光标当前位于哪个元素(textarea/input/where)中?似乎没有类似于
isfocused
的属性,您可以通过检查来确定特定文本字段是否具有焦点。但是,您可以为每个文本框的onFocus
事件创建一个事件处理程序,并让它在一个变量中记录新聚焦文本框的ID,以便稍后检查
此外,您可能会对以下内容感兴趣:它告诉您如何在给定字段中的当前光标位置插入文本(一旦您确定了哪个字段是焦点,例如使用上述方法)。所有浏览器的最新版本都支持document.activeElement。这将告诉您该窗口中当前有焦点的字段(光标所在的位置)。然后,您需要知道如何在当前光标位置插入文本。下面的函数就是这样做的
// Author: http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript
// Modified so it's safe across browser windows
function insertAtCursor(myField, myValue) {
var doc = myField.ownerDocument;
//IE support
if (doc.selection) {
myField.focus();
sel = doc.selection.createRange();
sel.text = myValue;
}
//FF, hopefully others
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) +
myValue + myField.value.substring(endPos, myField.value.length);
}
// fallback to appending it to the field
else {
myField.value += myValue;
}
}
因此,从弹出窗口中,按钮处理程序应该调用以下方法
// Pardon my contrived function name
function insertTextIntoFocusedTextFieldInOpener(text) {
var field = window.opener.document.activeElement;
if (field.tagName == "TEXTAREA" || (field.tagName == "INPUT" && field.type == "text" ) {
insertAtCursor(field, text);
}
}