javascript - 退格键无法正常工作

标签 javascript jquery

我构建了一个计算器,用户可以单击按钮,也可以从下拉列表中选择变量。使用键盘插入被拒绝。现在,当我单击用于退格功能的突出显示的后退箭头按钮时,即使使用鼠标将光标放置在表达式之间,也只会删除最右侧位置的字符。是否有解决方法可以删除光标所在位置之前的字符?我在左箭头单击时使用以下条件:

formulaText.value = formulaText.value.slice(0, formulaText.value.lastIndexOf("("));

enter image description here

最佳答案

您可以使用 input 元素上的 selectionStart 属性。更多信息请访问this MDN page 。下面是一个工作示例。

function getCursorPosition(id) {
  return document.getElementById(id).selectionStart;
}

function checkCursorPosition() {
  alert(getCursorPosition('testInput'));
}

function backspace() {
  var element = document.getElementById('testInput');
  var cursorPosition = getCursorPosition('testInput');
  
  element.value = element.value.substring(0, cursorPosition - 1) + element.value.substring(cursorPosition);
  element.selectionStart = element.selectionEnd = cursorPosition - 1;
}
<input type="text" id="testInput" value="Example text" />
<button onclick="checkCursorPosition()">Check Cursor Position</button>
<button onclick="backspace()">Backspace</button>

关于javascript - 退格键无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32636322/

相关文章:

javascript - 阻塞 CSS 资源

javascript - 拖放整个 div 容器。 (移动弹出Modal对话框)

javascript - 使用 iOS Safari 网络浏览器的全屏 html5 视频

jquery - 如何定位除 jquery 和 css 之外的所有标签 :not() selector

jquery - HTML、jQuery、Python - 表单文件上传 (GAE)

javascript - 没有每个和回调函数的 jQuery 循环

javascript - 使用 Jquery 对话框隐藏按钮

javascript - 使用 JS 遍历 SVG

javascript - Javascript 新日期函数中的奇怪行为

jquery - 向滚动类型相同的两个表添加垂直滚动 - HTML CSS JQuery