开发者

How can i use javascript to insert text into a textarea?

I n开发者_JAVA技巧eed to insert some text into a textarea at the place where the cursor is, how can i do this without jquery?


You may want to check the small code sample at:

  • Inserting at the cursor using JavaScript

Code from the above article:

function insertAtCursor(myField, myValue) {

  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
  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);
  } else {
    myField.value += myValue;
  }
}

// calling the function
insertAtCursor(document.getElementById('textarea_id'), 'sometext');


Please see this person's code here. This code uses the selection property of the document object to get the cursor position, and then builds a new string and stuffs it into the textarea. It also has a specialized routine for IE which has much more cumbersome logic for finding the cursor position.


Use an HTML title attribute? That will place tooltip text next to the cursor when it's over a particular element.

Or you could create a <div> with position: fixed, then position it at event.screenX, event.screenY:

<div id="tip" style="position: fixed; visibility: hidden;"></div>
<textarea onmousemove="position();" onmouseout="hide();"></texarea>
<script type="text/javascript">
  function position() {
    var d = document.getElementById('tip');
    d.style.visibility = 'visible';
    d.style.left = event.screenX + 'px';
    d.style.top = event.screenX + 'py';
  }
  function hide() {
    document.getElementById('tip').style.visibility = 'hidden';
  }
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜