光标自动定位到起始位置 contenteditable="true" ,v-html绑定内容,div可编辑时,光标移到最前面

出现这个问题原因:

(1)通过打断点可以看到,当你输入的时候触发input事件,提交值给父组件中的v-model;

(2)但因为在子组件中又监听了v-model的值,所以整体形成了闭环;

(3)还需要重点说明的是光标问题,contenteditable与v-html所在的元素值的改变如果不是通过输入而是通过赋值实现,光标就会跑到最前面;

所以以输入中文为例,你刚打了一个字母,立马就触发了监听与变动,光标移到最前面,自然无法完成整个正常的输入。

 

解决办法:

只有当blur的时候再做赋值操作(isChange为true),focus状态下不做赋值(isChange为false);

至于初始为true的原因是在父组件中直接给绑定的变量赋值时子组件中还是需要触发赋值的(isChange为true);

 

<template>
<div
class="div-editable"
contenteditable="true"
v-html="innerText"
@input="changeText"
@focus="isChange = false"
@blur="blurFunc"></div>
</template>
<script>
export default {
name: 'DivEditable',
props: {
value: {
type: String,
default: ''
}
},
data() {
return {
innerText: this.value,
isChange: true
}
},
watch: {
value() {
if (this.isChange) {
this.innerText = this.value
}
}
},
methods: {
changeText() {
this.$emit('input', this.$el.innerHTML)
},
blurFunc() {
this.isChange = true
this.$emit('blurFunc')
}
}
}
</script>
<style lang="scss">
.div-editable{
width: 100%;
height: 100%;
overflow-y: auto;
word-break: break-all;
outline: none;
user-select: text;
white-space: pre-wrap;
text-align: left;
&[contenteditable=true]{
user-modify: read-write-plaintext-only;
&:empty:before {
content: attr(placeholder);
display: block;
color: #ccc;
}
}
}
</style>

 

posted @   蓦然JL  阅读(169)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
  1. 1 唯一 G.E.M.邓紫棋
  2. 2 他只是经过 白敬亭 魏大勋
  3. 3 Uptown Funk Mark Ronson / Bruno Mars
  4. 4 在你的身边 盛哲
  5. 5 Edge of My Life Manafest
  6. 6 凄美地 郭顶
  7. 7 Wonderful Tonight Boyce Avenue
  8. 8 心如止水 Ice Paper
  9. 9 Sugar Maroon 5
  10. 10 静谧时光 JIAxNING
  11. 11 Right Now (Na Na Na) Aamir
  12. 12 Dangerously Charlie Puth
  13. 13 Someone You Loved Madilyn Paige
  14. 14 Shape of My Heart Boyce Avenue
  15. 15 We Can't Stop Boyce Avenue / Bea Miller
  16. 16 Perfect Boyce Avenue
  17. 17 Love Me Like You Do Boyce Avenue
  18. 18 Thank You Boyce Avenue
  19. 19 Don’t Wanna Know Boyce Avenue / Sarah Hyland
他只是经过 - 白敬亭 魏大勋
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

Not available

访问主页
关注我
关注微博
私信我
返回顶部
点击右上角即可分享
微信分享提示