admin管理员组文章数量:1122832
Suppose I have a script that intends to implement “smart brackets” in <textarea>
and <input>
elements: whenever the user types in a bracket or quotation mark character while selection is non-empty, the selection is wrapped inside an appropriate matching pair of brackets or quotation marks. The text, with the inserted surrounding brackets, stays selected. It looks like this:
document.addEventListener('keydown', ev => {
const input = ev.target.closest('input, textarea');
if (!input)
return;
if (input.selectionStart === input.selectionEnd)
return;
const surround = (op, cl) => {
ev.preventDefault();
const i0 = input.selectionStart;
const i1 = input.selectionEnd;
input.focus();
// execCommand preserves the undo stack, unlike assigning to .value
document.execCommand(
'insertText', false,
`${op}${input.value.substring(i0, i1)}${cl}`);
input.selectionStart = i0;
input.selectionEnd = i1 + `${op}${cl}`.length;
};
switch (ev.key) {
case '(':
return surround('(', ')');
case '[':
return surround('[', ']');
case '{':
return surround('{', '}');
case '"':
return surround('"', '"');
case "'":
return surround("'", "'");
}
}, false);
input, textarea { width: 100%; }
<textarea>select text and press an opening bracket…</textarea>
本文标签:
版权声明:本文标题:dom - How to ensure <textarea><input> selection set in a keydown handler stays in place in mobile br 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736281735a1926414.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论