Insert text on the current place of the cursor in the browser

房东的猫 提交于 2019-11-28 22:08:59

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!