在浏览器中的光标当前位置插入文本 [英] Insert text on the current place of the cursor in the browser

查看:470
本文介绍了在浏览器中的光标当前位置插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模态窗口,可以帮助格式化文本。
窗口上有多个textareas。
模态不应该附加到特定的textarea,所以当我在模态窗口中按下一个Icon时,我需要在光标当前的地方插入一个字符串/表情符号等。
我的问题,我怎么知道光标当前在哪个元素(textarea / input / whatever)?

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?

推荐答案

所有浏览器的最新版本都支持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.

// 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;
  }
}

因此,从弹出窗口,您的按钮处理程序应该调用以下方法

Therefore, from your popup, your button handler should call the following method

// 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);
  }
}

这篇关于在浏览器中的光标当前位置插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆