vah*_*det 2 javascript textarea selection vue.js vuetify.js
我尝试使用该方法setSelectionRange来更改 vuetify 中光标的位置v-textarea。
当我不操作v-model文本区域的属性引用的数据元素时,它效果很好。但是,如果我尝试先改变身体,然后再应用setSelectionRange方法;光标直接移动到文本末尾。
我附上了简化版本的片段。一旦您在文本区域中的任意位置按下退格键,光标就会移动到索引 2;但它会移动到文本的末尾。
然而,如果您再次删除this.body并退格,它就会平静地移动到索引 2。
new Vue({
el: '#app',
data: {
body: ''
},
created () {
this.body = 'I am initial body. Hit backspace on somewhere if you want!'
},
methods: {
onBackspaceOrDeleteButtonKeydown (event) {
// disable default behavior
event.preventDefault()
let bodyTextArea = this.$refs.pourBody.$el.querySelector('textarea')
// COMMENT OUT THE NEXT LINE TO SEE THE CURSOR MOVES TO INDEX 2 ALWAYS
this.body = 'I am changed body. My cursor should have moved to index 2 anyways, but it goes to the end like >'
bodyTextArea.setSelectionRange(2, 2)
}
}
})Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
<div id="app">
<v-app>
<v-content>
<v-container>
<v-textarea
ref="pourBody"
outline
v-model="body"
auto-grow rows="7"
@keydown.delete="onBackspaceOrDeleteButtonKeydown"
></v-textarea>
</v-container>
</v-content>
</v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
显然不setSelectionRange喜欢身体的变化。
我该如何解决这个问题?
将 setSelectionRange 包装到 setTimeout 中,如下所示setTimeout(() => bodyTextArea.setSelectionRange(2, 2))。将光标设置到所需位置并重置光标位置后,v-model 会重新渲染值。你必须确保setSelectionRange事后打电话。
| 归档时间: |
|
| 查看次数: |
3097 次 |
| 最近记录: |