Stop cursor from jumping to end of input field in javascript replace

匿名 (未验证) 提交于 2019-12-03 02:08:02

问题:

I'm using a regular expression to strip invalid characters out of an text input area in javascript (running in IE). I run the replace function on every keyup event. However, this makes the cursor jump to the end of the text box after each keypress, which makes inline editing impossible.

Here is it in action:

http://jsbin.com/ifufuv/2

Does anyone know how to make it so the cursor does not jump to the end of the input box?

回答1:

You'll have to manually put the cursor back where you want it. For IE9, set .selectionStart and .selectionEnd (or use .setSelectionRange(start, end)). For IE8 and earlier, use .createTextRange() and call .moveStart() on the text range.



回答2:

In addition to gilly3's answer, I thought someone might find it useful to see an actual code snippet.

In the example below, the selectionStart property is retrieved from the input element prior to the JavaScript string manipulation. Then selectionStart is set back to the initial position after the manipulation.

Depending on what you're trying to achieve, you could also access selectionEnd in place of selectionStart, and set a range: setSelectionRange(start, end).

document.getElementById('target').addEventListener('input', function (e) {   var target = e.target,       position = target.selectionStart; // Capture initial position      target.value = target.value.replace(/\s/g, '');  // This triggers the cursor to move.      target.selectionEnd = position;    // Set the cursor back to the initial position. });

The method .replace() will move the cursor's position, but you won't notice this.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!