【发布时间】:2021-01-19 16:21:04
【问题描述】:
我有一个函数可以获取用户在input 中键入的字符串的最后一个字符。但是如何使用execCommand() 选择那个单个字符?目标是将其复制到不同的input。
我试过element.select(),但没有结果。
要粘贴到新input 中的字符必须是原始输入中可见的字符,而不是与用户键入的键盘键对应的字符,因为这一切的原因是有一个外部 JS 库处理一些一个input中的CJK字符转换,并将结果移动到另一个..
我将采用复制粘贴的方法。因此,需要选择角色。但如果有更好的方法来实现它,请随时告诉我。
我对 Vanilla JavaScript 和 jQuery 方法持开放态度。
这是我的代码:
function copyPaste () {
var i1 = document.getElementById('userInput');
var i2 = document.getElementById('input2');
var c = i1.value.substr(lol.length - 1);
c.select();
document.execCommand('copy');
i2.focus();
document.execCommand('paste');
i1.focus();
}
input {
width: 255px;
}
button {
display: block;
margin: 20px 0;
text-align: left;
}
<input type="text" id="userInput" placeholder="First, type something here.">
<button type="button" onclick="copyPaste"();>Then, click here to copy the last character<br>of the above input into the next input.</button>
<input type="text" id="input2" value="Some text...">
【问题讨论】:
-
为什么要使用剪贴板?为什么不直接从第一个输入中读取值,并使用它将最后一个字符放在第二个输入中呢?此外,
execCommand是一个过时的功能...... -
现在粘贴是not supported
-
@trincot 我该怎么做?
-
我将其发布为答案。
标签: javascript select cjk execcommand