在 Vue 中,如果在一个元素上添加了 contenteditable="true" 属性,用户可以在该元素中输入和删除文本。但是,有时候在删除完内容后,光标会消失代码怎么实现
时间: 2024-02-25 16:53:58 浏览: 23
可以通过 Vue 自定义指令来实现。具体实现步骤如下:
1. 在 Vue 中注册自定义指令。
```javascript
Vue.directive('focus', {
inserted: function (el) {
el.focus();
}
})
```
2. 在模板中使用自定义指令,并将 v-model 指令绑定到数据上。
```html
<div contenteditable="true" v-model="content" v-focus></div>
```
3. 监听元素的 input 事件,当元素内容发生变化时,手动触发一次 input 事件,这样就可以保持光标位置不变了。
```javascript
Vue.directive('focus', {
inserted: function (el) {
el.focus();
},
update: function (el, binding, vnode) {
var s = binding.value;
if (s !== el.innerHTML) {
el.innerHTML = s;
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
el.dispatchEvent(new Event('input'));
}
}
})
```
通过以上代码,就可以实现在元素中输入和删除文本时保持光标位置不变的效果。