问题描述
我有4个输入文本标签和4个textarea标签,我需要创建一些热键,例如Ctrl + n,Ctrl + r和Ctrl + o,以便在所有文本字段的光标位置附加预定义的单词.
I have 4 input text tags and 4 textarea tags and I need to create some hotkey like Ctrl+n, Ctrl+r and Ctrl+o to append predefined words at the cursor position for all text fields.
我有此脚本,但仅用于onclick事件,因此我只想向用户显示一次文本(对于单词1按Ctrl + n,对于单词2按Ctrl + r,对于单词3按Ctrl + o),然后他不论他在哪个字段,只要每次输入一些文本,都可以插入这些单词.
I got this script but is only for onclick event, so I want just to show just one time for the user the text (Press Ctrl+n for word1, Ctrl+r for word2 and Ctrl+o for word3) then he can insert those words every time he is typing some text whatever the field he is.
<script>
function addText(event) {
var targ = event.target || event.srcElement;
document.getElementById("txt1").value += targ.textContent || targ.innerText;
}
</script>
<div onclick="addText(event)">word1</div>
<div onclick="addText(event)">word2</div>
<div onclick="addText(event)">word3</div>
<label><b>Text 1: </b></label><br>
<textarea rows="20" cols="80" id = "txt1" name="txt1"></textarea>
<label><b>Text2: </b></label>
<input type="text" size="69" name="txt2" value="">
推荐答案
您可以使用类似这样的内容.
请注意,我故意使用了未充分利用的键,因为某些控制键组合仅保留供浏览器使用,并且无法被网页中的客户端JavaScript拦截(例如 ctrl + N
或 ctrl + T
).
You can use something like this.
Please note that I've used underused keys on purpose since certain control key combinations are reserved for browser usage only and cannot be intercepted by the client side JavaScript in the web page (like ctrl+N
or ctrl+T
).
const arrKey = ['a', 'l', 'b'],
arrVal = ['addedA', 'addedL', 'addedB'];
function addText(event) {
if (event.target.classList.contains("addtext")) {
const index = arrKey.indexOf(event.key);
if (event.ctrlKey && index != -1) {
event.preventDefault();
insertAtCaret(event.target, arrVal[index]);
}
}
}
function insertAtCaret(el, text) {
const caretPos = el.selectionStart,
textAreaTxt = el.value,
newCaretPos = caretPos + text.length;
el.value = textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
el.setSelectionRange(newCaretPos, newCaretPos);
};
document.addEventListener('keydown', addText);
<label><b>Text 1: </b></label><br>
<textarea placeholder="Try ctrl+a or ctrl+b" rows="10" cols="40" id="txt1" name="txt1" class="addtext"></textarea><br/>
<label><b>Text 2: </b></label><br/>
<input type="text" size="40" name="txt2" class="addtext" value=""><br/>
<label><b>Text 3: </b></label><br>
<textarea rows="10" cols="40" id="txt3" name="txt1" class="addtext"></textarea><br/>
<label><b>Text 4: </b></label><br/>
<input type="text" size="40" name="txt4" class="addtext" value="">
这篇关于使用热键和javascript在textarea中附加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!