在按下键时替换文本字段中的字符



我有一个文本区,当我按Enter键时,我需要插入一个自定义{br}标记,而不是在新行上换行文本。我已经用CSS解决了换行问题,问题是当我按下回车键时,标签插入到字符串的末尾。我如何将它插入到输入的相同位置?

<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.selectionStarttextField.selectionEnd来获取光标位置。然后用substring()提取字符串的两个部分,并在

之间用{br}

连接。

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}

替换选中的文本

您当前将标记附加在textField的值之后。无论在你的textField中有什么,它总是会在最后添加它。

你必须得到你的光标的位置,并插入你的标签在这个位置在你的textField的值,也许使用像javascript切片我猜。

获取光标在文本区的位置

最新更新