热搜: 活动 交友 discuz
查看: 167|回复: 2

马黑黑老师 textarea符号补全演示

[复制链接]
发表于 2026-5-20 20:49:45 | 显示全部楼层 |阅读模式
<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>
 楼主| 发表于 2026-5-20 20:51:06 | 显示全部楼层
核心:event.key

textarea 文本框控件可以处理键盘按下、弹起、输入等事件,并通过 event.key 识别键位名称。键盘输入时(本例监听键位按下事件),当监听到符合 pairs 对象的键名时,自动补上其键值,就达成了符号补全的功能。自动补全函数还针对是否有文本被选中,两种情形插入自动补全符号时处理行为不同。

200

主题

1139

回帖

1万

积分

社区贵宾

积分
16110

最佳新人活跃会员热心会员推广达人宣传达人灌水之王突出贡献

发表于 2026-5-21 20:41:43 | 显示全部楼层
新知识~谢谢精彩分享
该会员没有填写今日想说内容.
返回列表 发新帖
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|小黑屋|纳兰音画网 ( 蜀ICP备2021011087号-1 )

GMT+8, 2026-11-16 09:01 , Processed in 0.051112 second(s), 22 queries .

Powered by Discuz! X5.0

© 2001-2020 Comsenz Inc.

快速回复 返回顶部 返回列表