|
<style>
.wrap { margin: 30px auto; width: 800px; height: 460px; }
#editor { width: 100%; height: 100%; box-sizing: border-box; padding: 10px; font-size: 1.5em; }
</style>
<div class="wrap">
<textarea id="editor" placeholder="输入小角括号引号等..."></textarea>
</div>
<script>
// 自动补全成对符号函数
function autoCompletePair(textarea, leftChar, rightChar) {
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const oldValue = textarea.value;
const selectedText = oldValue.substring(start, end);
let newText, cursorPos;
// 若有选中文本:包裹选中的内容
if (selectedText.length > 0) {
newText = leftChar + selectedText + rightChar;
cursorPos = start + leftChar.length + selectedText.length + rightChar.length;
textarea.value = oldValue.slice(0, start) + newText + oldValue.slice(end);
textarea.setSelectionRange(cursorPos, cursorPos);
// 若无选中文本:插入成对符号,光标置于中间
} else {
newText = leftChar + rightChar;
textarea.value = oldValue.slice(0, start) + newText + oldValue.slice(end);
textarea.setSelectionRange(start + 1, start + 1);
}
}
// 自动补全的成对符号设置(可以增补,但仅限于键盘符号)
const pairs = {
'(': ')',
'[': ']',
'{': '}',
'<': '>',
"'": "'",
'"': '"',
'`': '`',
};
// 编辑器 :按键按下
editor.onkeydown = (e) => {
if (pairs[e.key]) {
e.preventDefault(); // 阻止默认输入
autoCompletePair(editor, e.key, pairs[e.key]); // 调用自动补全函数
return;
}
};
</script>
|