更新输入值而不会丢失光标位置 [英] Updating an input's value without losing cursor position

查看:121
本文介绍了更新输入值而不会丢失光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在javascript替换中停止光标跳转到输入字段的结尾

我想使用JavaScript强制文本框的值为小写。我已经尝试了下面的代码,但每次按一下键时光标都会跳到输入的末尾。我该如何避免这种情况?

I want to mandate that the value of a text box is lowercase, using JavaScript. I've tried the code below, but the cursor jumps to the end of the input every time you press a key. How can I avoid this?

$("#beLowerCase").keyup(function(){
    $(this).val( $(this).val().toLowerCase() );
});


推荐答案

$("#beLowerCase").on('input', function(){

    // store current positions in variables
    var start = this.selectionStart,
        end = this.selectionEnd;

    this.value = this.value.toLowerCase();

    // restore from variables...
    this.setSelectionRange(start, end);
});

小提琴

这实际上也适用于CSS:

This actually works with CSS as well:

#beLowerCase{
  text-transform:lowercase;
}

服务器可以处理实际的下壳...

And server can take care of the actual lower-casing...

这篇关于更新输入值而不会丢失光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆