javascript - 前进和后退按钮在插入符号位置处使用react

标签 javascript html button input onclick

尝试使用键盘登录的想法。 我需要制作前进和后退按钮。 后退和前进按钮似乎处于插入符号位置。 输入被禁用,仅使用按钮单击。 如何调整按钮 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。 提前谢谢您!

最佳答案

我使用 selectionStartselectionEnd 来检查插入符位置

这是您要找的东西

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/

相关文章:

javascript - 有没有一种工具可以在部署时自动缩小 html 文件中引用的所有 javascript 文件?

java - 如何测量 Java 中按钮所需的大小

javascript - 如何按范围替换字符串?

javascript - 如何在AG网格中默认折叠边栏

php - 5 秒后自动关闭 HTML 页面

javascript - Bootstrap 导航项未出现在移动设备中

Flutter:将视频制作为圆形按钮

android - 为什么我的 ImageView 元素与我的 Button 混在一起?

javascript - 为什么 Javascript minifiers 将 === 转换为 ==?

html - 在样式标签中编辑滚动条