实现点击按钮在输入框中的光标位置插入一段文本
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert Text at Cursor Position</title>
</head>
<body>
<textarea id="myTextarea"></textarea>
<button onclick="insertTextAtCursor('Insert this text')">Insert Text</button>
<script>
function insertTextAtCursor(text) {
var textarea = document.getElementById("myTextarea");
var cursorPosition = textarea.selectionStart;
var textBeforeCursor = textarea.value.substring(0, cursorPosition);
var textAfterCursor = textarea.value.substring(cursorPosition, textarea.value.length);
textarea.value = textBeforeCursor + text + textAfterCursor;
// Move cursor to the end of inserted text
textarea.selectionStart = textarea.selectionEnd = cursorPosition + text.length;
}
</script>
</body>
</html>