如何使用javascript将文本插入textarea? [英] How can i use javascript to insert text into a textarea?

查看:95
本文介绍了如何使用javascript将文本插入textarea?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在光标位置的textarea中插入一些文本,如何在没有jquery的情况下执行此操作?

I need 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

上述文章中的代码:

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

这篇关于如何使用javascript将文本插入textarea?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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