javascript - 在 keydown 上替换文本字段中的字符
问题描述
我有一个文本区域,当我按 Enter 时,我需要插入一个自定义 {br} 标签,而不是将文本换行。我已经解决了 CSS 的换行问题,问题是当我按 enter 时,标签会插入到字符串的末尾。如何将它插入到输入的相同位置?
HTML
<textarea class="form-control d-inline-block ml-3 my-auto" rows="1" value="" onkeydown="tagOnInput(this, window.event.keyCode)"></textarea>
CSS
textarea[rows="1"] {
overflow: auto;
white-space: nowrap;
}
JS
function tagOnInput(textField, key){
if (key === 13) {
textField.value = textField.value + "{br}"; // Tag is added at the end, but should be in the cursor position.
}
}
解决方案
您可以使用textField.selectionStart
andtextField.selectionEnd
来获取光标位置。然后使用substring()
提取String的两部分,并将两者与{br}
in between
const el = document.getElementById("area")
const btn = document.getElementById("btn")
area.addEventListener('keydown', (e) => {
if (e.which === 13) {
e.preventDefault()
const selectionStart = el.selectionStart
const selectionEnd = el.selectionEnd
const value = el.value
const toInsert = '{br}'
const partLeft = value.substr(0, selectionStart)
const partRight = value.substr(selectionEnd)
el.value = partLeft + toInsert + partRight
el.focus()
el.selectionEnd = selectionEnd + toInsert.length
el.selectionStart = selectionEnd + toInsert.length
}
})
<label>Textarea</label>
<textarea id="area"></textarea>
如果没有选择文本,这将插入到光标位置。如果他是,这会将所选文本替换为{br}