当前位置: 首页> 健康> 知识 > 南通专业网站设计制作_小程序用什么语言开发_淘宝关键词工具_淘客推广

南通专业网站设计制作_小程序用什么语言开发_淘宝关键词工具_淘客推广

时间:2025/7/9 4:09:49来源:https://blog.csdn.net/q1003675852/article/details/142254311 浏览次数:0次
南通专业网站设计制作_小程序用什么语言开发_淘宝关键词工具_淘客推广

一、问题描述

使用v-model绑定的textarea如果需要改变其内容,一般只要改变v-model对应的变量即可,但如果需要在textarea的当前光标位置插入指定文本,那就需要操作DOM了。于是我们写了一段js:

const insertTextAtCursor = (text) => {const textarea = document.querySelector('textarea')if (textarea) {const startPos = textarea.selectionStartconst endPos = textarea.selectionEndconst value = textarea.valueconst beforeText = value.substring(0, startPos)const afterText = value.substring(endPos, value.length)const newValue = beforeText + text + afterTexttextarea.value = newValuetextarea.selectionStart = textarea.selectionEnd = startPos + text.length}
}

但如果直接调用上述代码的insertTextAtCursor 函数,就会发现一些古怪的现象,比如下面点击[插入客户昵称],就会在textarea的当前光标处插入指定文本,但实际插入却不理想:
请添加图片描述

二、解决方案

上述问题产生的原因跟textarea.value与v-model直接产生了冲突,于是只要改一下代码:

const insertTextAtCursor = (text) => {const textarea = document.querySelector('textarea')if (textarea) {const startPos = textarea.selectionStartconst endPos = textarea.selectionEndconst value = textarea.valueconst beforeText = value.substring(0, startPos)const afterText = value.substring(endPos, value.length)const newValue = beforeText + text + afterTextform.value.next_visit_content = newValuenextTick(() => {textarea.selectionStart = textarea.selectionEnd = startPos + text.length})}
}
关键字:南通专业网站设计制作_小程序用什么语言开发_淘宝关键词工具_淘客推广

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: