猿问

输入事件时,输入光标跳至输入字段的末尾

我正在尝试在输入事件时将用户输入转换为大写


因此,每当我在输入字段中键入键时,都会遇到以下问题


当用户在中间输入时,光标跳到输入值的末尾。

最后键入的字符(不是最后一个字符)不会转换为大写。

这是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>


慕哥6287543
浏览 466回答 3
3回答

猛跑小猪

我能够解决您的问题,但是您需要在代码中引入一个新变量HTML:<div id="app">&nbsp; &nbsp;<input type="text" v-model="input" @input="handleInput">&nbsp; &nbsp;<p>{{ updated_value }}</p></div>JS:new Vue({&nbsp; &nbsp;el: "#app",&nbsp; &nbsp;data() {&nbsp; &nbsp; &nbsp; &nbsp;return {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;input: null,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;updated_value: null&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;},&nbsp; &nbsp;methods: {&nbsp; &nbsp; &nbsp; &nbsp;handleInput(e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.input = e.target.value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.updated_value = e.target.value ? e.target.value.toString().toUpperCase()&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;: e.target.value;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}});摘要:1)使用新变量(updated_value)存储输入的大写版本,并将其用作<p>2的值。这确保输入值不会被更新,从而不会导致游标跳转的问题
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答