javascript - 使用javascript打字时如何避免光标向后移动

标签 javascript

在文本框中输入值时,当我在输入值之间输入值时,光标会自动移动到值的末尾。

<!DOCTYPE html>
<html>
    <body>
        <script>
        function truncate(x) {
            if(x.value.length > 0) 
            {               
                x.value = x.value.replace(/^\s+/, '');
            }
        }
        </script>

        <input id="otherText" onkeyup="javascript:truncate(this);" maxlength="12" type="text"/>

    </body>
</html>

最佳答案

<!DOCTYPE html>
<html>
<body>



<script>
function truncate(x){
var val = document.getElementById("otherText");

var inputTextValue = val.value;
if(inputTextValue.length>0) 
    { 

    val.value = '';

}
}
</script>
<input id="otherText" onkeyup="javascript:truncate(this);"   maxlength="12" type="text"/> </body>
</html>

请注意,我不知道如何用特定的正则表达式替换字符串。但上面的代码只是替换为空字符串。您可以根据您的要求进行修改。

关于javascript - 使用javascript打字时如何避免光标向后移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15271600/

相关文章:

javascript - 为什么 new Date(1970, 0 ,1).getFullYear() 返回 1969?

javascript - Angular 过滤表达式

javascript - 从对象数组中提取数据并按字母顺序排序(同时)

javascript - 做一个动态/掩码变量?

javascript - Angular 1.0.8 : How to skip an iteration in ng-repeat

javascript - 带 for 循环的 setInterval/setTimeOut 函数显示意外结果

javascript - 函数(全局){...}(这个)如何工作?

Javascript:将参数传递给回调调用的方法

javascript - 从 2 个特定元素创建网格

javascript - 除表头外的表无法正常工作 html