html textarea 插入字符在光标处

  • Post author:
  • Post category:其他


textarea 插入字符在光标处



前言



深度解析



1 效果图

在这里插入图片描述



上代码

<!DOCUMENT>

<html>

<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<script>

function myFunction(){
	//alert(12341234);
	var demoStr = "uuuuuuuuu";
	var CodeArea = document.getElementById('CodeArea');
	var res = GetSelectedText(CodeArea, 'index');//传index获取当前位置
	 
	ChangeSelectedText(CodeArea, demoStr);//str传值
}

 
//获取光标位置,或者选中内容
 
function GetSelectedText(obj, type) {
	debugger;
	var userSelection;
	if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
		// 非IE浏览器
		// 获取选区的开始位置
		var startPos = obj.selectionStart,
				  // 获取选区的结束位置
			endPos = obj.selectionEnd;
		//console.log("非IE:")
		//console.log("选区开始点:" + startPos + ',选区结束点:' + endPos)
		if (type == "index") {
			if (obj.selectionStart == obj.textLength) {
				userSelection = "*#文本末尾#*";
			}
		} else {
			userSelection = obj.value.substring(startPos, endPos)
		}
	} else if (document.selection) {
		// IE浏览器
		console.log("IE:")
		userSelection = document.selection.createRange().text
	}

	return userSelection
}
//在光标位置插入新的内容
function ChangeSelectedText(obj, str) {
	if (window.getSelection) {
		// 非IE浏览器
		//console.log("非IE:")
		obj.setRangeText(str);
		//  在未选中文本的情况下,重新设置光标位置
		obj.selectionStart += str.length;
		obj.focus()
	} else if (document.selection) {
		// IE浏览器
		//console.log("IE:")
		obj.focus();
		var sel = document.selection.createRange();
		sel.text = str;
	}
}

</script>
</head>


<body>
<textarea id="CodeArea" >
</textarea>
<button onclick="myFunction()">Click me</button>


</body>
</html>



版权声明:本文为qq_41113916原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。