Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery:光标自动放置在val()的末尾_Jquery_Input_Cursor_Keyup - Fatal编程技术网

Jquery:光标自动放置在val()的末尾

Jquery:光标自动放置在val()的末尾,jquery,input,cursor,keyup,Jquery,Input,Cursor,Keyup,我使用javascript代码在注册时清除用户名。如果不允许使用字符,则将其替换为破折号 我的问题< /强>是:当用户想要在文本中间添加字符时,光标为“强”,自动放置在输入的结束< /强>。 您可以在此处进行测试: HTML: Username : <input type="text" id="username" />​ 有什么想法吗 谢谢没有好的方法,但是插件应该可以减轻一些痛苦。您可以使用插件(也被提及)。请查看: $("#username").bind({ keydo

我使用javascript代码在注册时清除用户名。如果不允许使用字符,则将其替换为破折号

我的<强>问题< /强>是:当用户想要在文本中间添加字符时,光标为“强”,自动放置在输入的结束< /强>。

您可以在此处进行测试:

HTML:

Username : <input type="text" id="username" />​
有什么想法吗


谢谢

没有好的方法,但是插件应该可以减轻一些痛苦。

您可以使用插件(也被提及)。请查看:

$("#username").bind({
    keydown: function() {
        var $this = $(this);
        $this.data("pos", $this.caret().start);
    },
    keyup: function() {
        var $this = $(this),
            pos = $this.data("pos"),
            value = clean_username(this.value);
        if (value !== this.value) {
            this.value = value;
            $this.caret(pos + 1, pos + 1);
        }
    }
});​

演示:

如果我键入一个单词,并将光标放在字符之间,然后点击“空格”,光标仍会移动到此小提琴中单词的末尾
$("#username").bind({
    keydown: function() {
        var $this = $(this);
        $this.data("pos", $this.caret().start);
    },
    keyup: function() {
        var $this = $(this),
            pos = $this.data("pos"),
            value = clean_username(this.value);
        if (value !== this.value) {
            this.value = value;
            $this.caret(pos + 1, pos + 1);
        }
    }
});​