[英]Stop re positioning of the cursor
I have a number formatter in angular. 我有一个角度数字格式化程序。
I need to get the cursor positioned in the place where i perform insert or delete a number. 我需要将光标定位在执行插入或删除数字的位置。
Currently after the insert or delete the cursor gets appended in the end(I dont need this behavior i want the cursor to stay there) 当前在插入或删除光标后附加到末尾(我不需要这种行为,我希望光标停留在那儿)
// This runs when we update the text field
ngModelCtrl.$parsers.push(function(viewValue) {
return viewValue.replace(/,/g, '');
})
My working code is please feel free to fork from here 我的工作代码可以从这里随意进行
You could use the selectionStart
and selectionEnd
properties of an input field to get the current cursor position, then the setSelectionRange()
method to set it once the value has been updated (See here for API reference). 您可以使用输入字段的selectionStart
和selectionEnd
属性获取当前光标位置,然后使用setSelectionRange()
方法在值更新后对其进行设置(有关API参考,请参见此处 )。
To do this, you can modify the keydown
event handler to store the value before change (including commas) and the cursor position: 为此,您可以修改keydown
事件处理程序以存储更改前的值(包括逗号)和光标位置:
$element.bind('keydown', function(event) {
// Store previous value (including commas) and cursor position
prevVal = $element.val();
start = $element[0].selectionStart;
end = $element[0].selectionEnd;
if (key == 46) {
// Delete pressed, so increment cursor position
start++;
end++;
}
...
});
The above code increments the cursor position if the delete key is pressed (instead of backspace) as the cursor position will remain the same then (taking into account the currency formatting commas of course). 如果按下删除键(而不是退格键),以上代码将增加光标位置,因为此时光标位置将保持不变(当然要考虑货币格式的逗号)。
The listener
function can then be modified to calculate the difference in length of the currency value (including formatting commas) and set the cursor position accordingly after typing a key: 然后可以修改listener
功能以计算货币值的长度差(包括格式逗号),并在键入键后相应地设置光标位置:
var listener = function() {
...
// Calculate new cursor position and update
var diff = $element.val().length - prevVal.length;
$element[0].setSelectionRange(start+diff, end+diff);
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.