我构建了一个计算器,用户可以单击按钮,也可以从下拉列表中选择变量。使用键盘插入被拒绝。现在,当我单击用于退格功能的突出显示的后退箭头按钮时,即使使用鼠标将光标放置在表达式之间,也只会删除最右侧位置的字符。是否有解决方法可以删除光标所在位置之前的字符?我在左箭头单击时使用以下条件:
formulaText.value = formulaText.value.slice(0, formulaText.value.lastIndexOf("("));
最佳答案
您可以使用 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/