尝试使用键盘登录的想法。 我需要制作前进和后退按钮。 后退和前进按钮似乎处于插入符号位置。 输入被禁用,仅使用按钮单击。 如何调整按钮 A 和 B,使其不仅在值的末尾键入,而且将字母放置在插入符位置处?
function A(){ document.getElementById('user').value += "A"; }
function B(){ document.getElementById('user').value += "B"; }
function BackSpace(){document.getElementById('user').value=document.getElementById('user').value.substring(0,document.getElementById('user').value.length - 1);}
function Back(){
user.focus();
console.log(user.selectionStart-1);
if(user.selectionStart > 0 ){user.focus();
user.selectionEnd = user.selectionStart-1;
user.selectionStart = user.selectionStart;}}
function Forward(){
console.log(user.selectionStart);
user.focus();
user.selectionEnd = user.selectionStart+1;
user.selectionStart = user.selectionStart+1;}
<div>
<button type="button" id="userKeysIn">
<span class="">Username</span>
<input id="user" disabled="disabled" type="text" name="user">
</button>
</div>
<div>
<button type="button" onclick="A();">a</button>
<button type="button" onclick="B();">b</button>
<button type="button" onclick="BackSpace();">Backspace</button>
<button type="button" onclick="Back();">Back</button>
<button type="button" onclick="Forward();">Forward</button>
</div>
请不要使用 JQuery。 提前谢谢您!
最佳答案
我使用 selectionStart
和 selectionEnd
来检查插入符位置
这是您要找的东西
String.prototype.replaceBetween = function(start, end, what) {
return this.substring(0, start) + what + this.substring(end);
};
function writeValue(value) {
var userInput = document.getElementById('user');
var inputValue = document.getElementById('user').value;
if (userInput.selectionStart === userInput.selectionEnd) {
inputValue = inputValue.substring(0, userInput.selectionStart) + value + inputValue.substring(userInput.selectionStart, inputValue.length);
} else {
inputValue = inputValue.replaceBetween(userInput.selectionStart, userInput.selectionEnd, value);
}
document.getElementById('user').value = inputValue;
}
function A(){
writeValue("A");
}
function B(){
writeValue("B");
}
请参阅codepen
关于javascript - 前进和后退按钮在插入符号位置处使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49663274/