我有一个contenteditable p元素。我想将可能的编辑操作限制为插入和删除逗号。我还想将更新的内容复制到另一个div. 这两个目标似乎很难结合起来:如果按下退格键或逗号以外的任何其他键,我似乎必须监听keydown事件以防止文本更改event.preventDefault()。当我听keyup, 时event.preventDefault()执行得太晚,无论按下哪个键,内容都会更新。但我可能需要等待keyup更新段落的内容,以便我可以复制文本。如果我使用keydown,我会得到原文。我正在使用Vue。在 HTML 代码中,@keydown='evaluate($event)'只需附加一个侦听器并允许使用访问事件变量。编辑:这是我的原始代码,另请参阅下面的代码段(不含 Vue)。HTML<p @keydown='evaluate($event)' id='text' contenteditable> Some text</p>JSevaluate: function(storeResponse = true, event) { // Stop if any key except comma or backspace was pressed. Only works well with keydown. if (! [',', 'Backspace'].includes (event.key)) { event.preventDefault(); return; } // Otherwise, copy the updated content. Only works well with keyup. let textContent = document.getElementById('text').textContent; // Paste updated content to another p document.getElementById('original-text').innerText = textContent;}document.getElementById('text').addEventListener('keydown', evaluate);function evaluate() { // Stop if any key except comma or backspace was pressed. // Only works well with keydown. if (![',', 'Backspace'].includes(event.key)) { event.preventDefault(); return; } // Otherwise, copy the updated content. Only works well with keyup. let textContent = document.getElementById('text').textContent; // I need to paste the updated content to another div, but just log it for this snippet console.log(textContent);}<p @keydown='evaluate' id='text' contenteditable> Some text</p>有没有一种优雅的方法来限制可能的编辑操作并获取更新的文本?
添加回答
举报
0/150
提交
取消