搜索
热搜: 活动 交友 discuz
查看: 6|回复: 1

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

[复制链接]
  • TA的每日心情
    开心
    昨天 20:40
  • 签到天数: 414 天

    连续签到: 11 天

    [LV.9]以坛为家II

    464

    主题

    1248

    回帖

    1万

    积分

    社区管理员

    积分
    13121

    最佳新人活跃会员热心会员推广达人宣传达人灌水之王突出贡献优秀版主荣誉管理

    发表于 昨天 20:49 | 显示全部楼层 |阅读模式
    <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>
  • TA的每日心情
    开心
    昨天 20:40
  • 签到天数: 414 天

    连续签到: 11 天

    [LV.9]以坛为家II

    464

    主题

    1248

    回帖

    1万

    积分

    社区管理员

    积分
    13121

    最佳新人活跃会员热心会员推广达人宣传达人灌水之王突出贡献优秀版主荣誉管理

     楼主| 发表于 昨天 20:51 | 显示全部楼层
    核心:event.key

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

    本版积分规则

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

    GMT+8, 2026-5-21 03:38 , Processed in 0.081344 second(s), 22 queries .

    Powered by Discuz! X3.5

    © 2001-2020 Comsenz Inc.

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