前言
深度解析
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(){
var demoStr = "uuuuuuuuu";
var CodeArea = document.getElementById('CodeArea');
var res = GetSelectedText(CodeArea, 'index');
ChangeSelectedText(CodeArea, demoStr);
}
function GetSelectedText(obj, type) {
debugger;
var userSelection;
if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
var startPos = obj.selectionStart,
endPos = obj.selectionEnd;
if (type == "index") {
if (obj.selectionStart == obj.textLength) {
userSelection = "*#文本末尾#*";
}
} else {
userSelection = obj.value.substring(startPos, endPos)
}
} else if (document.selection) {
console.log("IE:")
userSelection = document.selection.createRange().text
}
return userSelection
}
function ChangeSelectedText(obj, str) {
if (window.getSelection) {
obj.setRangeText(str);
obj.selectionStart += str.length;
obj.focus()
} else if (document.selection) {
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>