[英]Input cursor jumps to end of input field on input event
我正在尝试将输入事件的用户输入转换为大写
所以,每当我在输入字段中键入一个键时,我就会遇到以下问题
这是JS小提琴https://jsfiddle.net/aeL051od/的链接,以重现该问题
new Vue({ el: "#app", data() { return { input: null } }, methods: { handleInput(e) { this.input = e.target.value ? e.target.value.toString().toUpperCase() : e.target.value; } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <input type="text" v-model="input" @input="handleInput"> {{ input }} <!-- {{ input }} is just for reference --> </div>
如果您(或Vue)将新值复制到输入中,则光标将设置为输入的结尾。 如果要保留先前的位置,则需要捕获位置,进行更改,然后在$nextTick
恢复位置。
另请注意,如果要在处理程序中设置this.input
,那么使用v-model
也没有意义。 保存event
也不太可能,但你可以。
new Vue({ el: "#app", data() { return { input: null, event: null } }, methods: { handleInput(e) { const el = e.target; const sel = el.selectionStart; const upperValue = el.value.toUpperCase(); el.value = this.input = upperValue; this.event = e; this.$nextTick(() => { el.setSelectionRange(sel, sel); }); } } });
#app { background: #fff; border-radius: 4px; padding: 20px; transition: all 0.2s; } input { margin-bottom: 20px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <input type="text" @input="handleInput"> <p>{{ event ? event.target.value : null }}</p> <p> {{input}} </p> </div>
{{ event ? event.target.value : null }}
{{ event ? event.target.value : null }}
在这里显示目标值。
你必须显示转换后的input
值。 应该如下
<div id="app">
<input type="text" v-model="input" @input="handleInput">
<p>{{ input }}</p>
</div>
对于光标跳转问题,获取光标在开始时的位置,然后在更新值后将光标设置为开始位置
handleInput(e) {
var start = e.target.selectionStart;
this.input = this.input.toUpperCase()
this.$nextTick(()=>{
e.target.selectionStart = e.target.selectionEnd = start;
})
}
小提琴: https : //jsfiddle.net/r53ecug6/
我能够解决您的问题,但您需要在代码中引入一个新变量
HTML:
<div id="app">
<input type="text" v-model="input" @input="handleInput">
<p>{{ updated_value }}</p>
</div>
JS:
new Vue({
el: "#app",
data() {
return {
input: null,
updated_value: null
}
},
methods: {
handleInput(e) {
this.input = e.target.value;
this.updated_value = e.target.value ? e.target.value.toString().toUpperCase()
: e.target.value;
}
}
});
摘要:
1)使用新变量(updated_value)存储输入的大写版本并将其用作<p>
的值
2)这确保输入值不被更新,因此不会导致光标问题跳跃
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.