【问题标题】:Stop cursor from jumping to end of input field in javascript replace在javascript替换中阻止光标跳转到输入字段的末尾
【发布时间】:2012-01-03 09:56:07
【问题描述】:

我正在使用正则表达式从 javascript(在 IE 中运行)的文本输入区域中去除无效字符。我在每个 keyup 事件上运行替换功能。但是,这会使光标在每次按键后跳转到文本框的末尾,从而无法进行内联编辑。

下面是实际操作:

http://jsbin.com/ifufuv/2

有没有人知道如何让光标不跳到输入框的末尾?

【问题讨论】:

标签: javascript replace


【解决方案1】:

我遇到了同样的问题,我发现https://www.sitepoint.com/6-jquery-cursor-functions/ 有解决方案。这里有 6 种方法可以让您在输入/文本区域中获取/设置光标位置。我相信这也适用于内容可编辑字段!

这非常有用,因为该错误仅针对 IE 和 Windows 7 组合显示。

这是我之前的代码

$body.on('input paste','.replace-special-chars',function () {
    let coma = /‚/g;
    let doubleQuotes = /[“”]/g;
    let singleQuotes = /[‘’]/g;
    $(this).val($(this).val().replace(doubleQuotes,'"'));
    $(this).val($(this).val().replace(coma,','));
    $(this).val($(this).val().replace(singleQuotes,"'"));
    $(this).val($(this).val().replace(/[^\x00-\xff]/g, '- '));
});

以及我在上面提到的网站上找到的使用 jquery 方法的后续代码

$body.on('input paste','.replace-special-chars',function () {
    let position = $(this).getCursorPosition();
    let coma = /‚/g;
    let doubleQuotes = /[“”]/g;
    let singleQuotes = /[‘’]/g;
    $(this).val($(this).val().replace(doubleQuotes,'"'));
    $(this).val($(this).val().replace(coma,','));
    $(this).val($(this).val().replace(singleQuotes,"'"));
    $(this).val($(this).val().replace(/[^\x00-\xff]/g, '- '));
    $(this).setCursorPosition(position);
});

【讨论】:

    【解决方案2】:

    除了gilly3's answer,我想有人可能会发现查看实际代码 sn-p 很有用。

    在下面的示例中,selectionStart 属性是在 JavaScript 字符串操作之前从 input 元素中检索的。然后将selectionStart 设置回初始位置 操作之后。

    根据您要实现的目标,您还可以访问selectionEnd 代替selectionStart,并设置范围: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.
    });
    <p>The method <code>.replace()</code> will move the cursor's position, but you won't notice this.</p>
    <input type="text" id="target" />

    【讨论】:

    【解决方案3】:

    您必须手动将光标放回您想要的位置。对于 IE9,设置.selectionStart.selectionEnd(或使用.setSelectionRange(start, end))。对于 IE8 及更早版本,使用 .createTextRange() 并在文本范围内调用 .moveStart()

    【讨论】:

    • W3Schools 有一个关于如何使用 onkeypress 取消键的精彩示例(在他们的示例中,它取消了数字,并且您似乎有足够的能力修改正则表达式以取出您不想要的字符) . w3schools.com/jsref/event_onkeypress.asp
    • @Mike:W3Schools 真的不值得像你这样的人为他们宣传他们的网站。看看w3fools.com - w3s 上的很多信息是错误的,或者是在宣传开发人员的不良做法。网上有很多更好的资源,比如quirksmode.orgdeveloper.mozilla.org
    • 公平一点,我不知道该网站的问题。
    • 请参阅stackoverflow.com/questions/3286595/…,了解我对这项基本技术的实现。
    猜你喜欢
    • 2020-07-29
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2014-10-09
    • 2011-10-25
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多