JS基于textarea的键盘成对符号自动补全

位置: 首页 > 代码集锦
[发布: 2026.5.20  作者: 马黑  阅读: 40]
<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>

前一篇: JS打开本地文本文件演示
下一篇: 使用CSS Custom Highlight API做全文多彩字

发表评论:

  
 

评论列表 [0条]

Copyright © 2023 All Right Reserved 马黑PHP文章管理整站系统v1.8
联系我们: gxblk@163.com