我正在尝试在我的应用程序中重现类似于 Microsoft Excel/Google 表格的用户体验,当您键入公式时,您可以使用自动完成下拉列表来选择不同的公式和变量。
为此,在验证自动完成后,我希望能够控制光标的位置。
例如,如果我键入 =sum(variable1, variable2),在自动完成 variable2 时,光标应该在最后一个括号之前,而不是在最后。
我了解如何使用 javascript 设置光标的位置,问题是因为我同时修改了输入的值并设置了光标位置,后者不起作用。
我在 fiddle 上用一个更简单的上下文重现了这个问题: https://jsfiddle.net/joparisot/j8ourfa1/31/
我的 html:
<div id="app">
<autocomplete v-model="selection"></autocomplete>
</div>
<template id="autocomplete">
<div>
<h2>gernerogrnio</h2>
<input id="my-input"
class="form-control"
type="text"
:value="value"
@keydown.enter="updateValue($event.target.value)">
<p>{{ value }}</p>
</div>
</template>
我的脚本:
Vue.component('autocomplete', {
template: '#autocomplete',
props: {
value: {
type: String,
required: true
}
},
methods: {
updateValue (value) {
var new_value = ''
if (value.length < 4) {
new_value = 'Inferior'
} else {
new_value = 'Superior'
}
this.$emit('input', new_value)
var myInput = document.getElementById('my-input');
this.setCaretPosition(myInput, 5)
},
setCaretPosition(ctrl, pos) {
ctrl.focus();
ctrl.setSelectionRange(pos, pos);
}
}
});
new Vue({
el: '#app',
data: {
selection: 'test'
}
});
我不关心自动完成,但根据您键入的内容,当您按回车键时,输入将填充一个新值。可以看到,如果注释掉第11到16行,直接设置new_value为value,那么设置光标位置就可以了。
我似乎不能同时做这两件事。有什么想法吗?
最佳答案
感谢 Roy J 的评论,我得以找到解决方案。
在 updateValue 函数中添加以下内容:
this.$nextTick(() => {
this.setCaretPosition(myInput, 5)
});
关于Javascript:更改输入值时设置光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48868075/