当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS实现在文本指定位置插入内容的简单示例

JS实现在文本指定位置插入内容的简单示例

2018年02月18日  | 移动技术网IT编程  | 我要评论
实例如下所示: function insertatcursor(myfield, myvalue) { //ie 浏览器 if (documen

实例如下所示:

function insertatcursor(myfield, myvalue) { 
 
 //ie 浏览器 
 if (document.selection) { 
  myfield.focus(); 
  sel = document.selection.createrange(); 
  sel.text = myvalue; 
  sel.select(); 
 } 
 
 //firefox、chrome等 
 else if (myfield.selectionstart || myfield.selectionstart == '0') { 
  var startpos = myfield.selectionstart; 
  var endpos = myfield.selectionend; 
 
  // 保存滚动条 
  var restoretop = myfield.scrolltop; 
  myfield.value = myfield.value.substring(0, startpos) + myvalue + myfield.value.substring(endpos, myfield.value.length); 
  
  if (restoretop > 0) { 
  myfield.scrolltop = restoretop; 
  } 
  
  myfield.focus(); 
  myfield.selectionstart = startpos + myvalue.length; 
  myfield.selectionend = startpos + myvalue.length; 
 } else { 
  myfield.value += myvalue; 
  myfield.focus(); 
 } 
} 
<textarea id="textarea" style="width: 386px; height: 260px"> 
</textarea> 
<input type="text" id="text" /> 
<input type="button" value="插入" onclick="insertatcursor(document.getelementbyid('textarea'),document.getelementbyid('text').value)" /> 

以上这篇js实现在文本指定位置插入内容的简单示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网