您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在使用JavaScript / jquery的游标中插入文本

在使用JavaScript / jquery的游标中插入文本

从这里使用:

function insertAtCaret(areaId, text) {

  var txtarea = document.getElementById(areaId);

  if (!txtarea) {

    return;

  }



  var scrollPos = txtarea.scrollTop;

  var strPos = 0;

  var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?

    "ff" : (document.selection ? "ie" : false));

  if (br == "ie") {

    txtarea.focus();

    var range = document.selection.createRange();

    range.moveStart('character', -txtarea.value.length);

    strPos = range.text.length;

  } else if (br == "ff") {

    strPos = txtarea.selectionStart;

  }



  var front = (txtarea.value).substring(0, strPos);

  var back = (txtarea.value).substring(strPos, txtarea.value.length);

  txtarea.value = front + text + back;

  strPos = strPos + text.length;

  if (br == "ie") {

    txtarea.focus();

    var ieRange = document.selection.createRange();

    ieRange.moveStart('character', -txtarea.value.length);

    ieRange.moveStart('character', strPos);

    ieRange.moveEnd('character', 0);

    ieRange.select();

  } else if (br == "ff") {

    txtarea.selectionStart = strPos;

    txtarea.selectionEnd = strPos;

    txtarea.focus();

  }



  txtarea.scrollTop = scrollPos;

}


<textarea id="textareaid"></textarea>

<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>
javascript 2022/1/1 18:15:08 有494人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶