Insert text on the current place of the cursor in

2019-01-23 00:31发布

问题:

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?

回答1:

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


回答2:

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 the onFocus 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).