📌  相关文章
📜  如何在 javascript 输入中自动关闭括号 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:01:40.995000             🧑  作者: Mango

代码示例1
const closeChars = new Map([
  ['{', '}'],
  ['[', ']'],
  ['(', ')']
]);
    
maintextarea=document.getElementById('maintextarea');

maintextarea.addEventListener('input', function (e) {

    const pos = e.target.selectionStart;
    const val = [...e.target.value];
    
    const char = val.slice(pos-1, pos)[0];
    const closeChar = closeChars.get(char);
    
    if (closeChar) {
      val.splice(pos, 0, closeChar);
      e.target.value = val.join('');
      e.target.selectionEnd = pos;
    }
});