js 给选中的文字添加颜色、替换文字内容...,选中状态去除后更改还在(document.execCommand)

操作说明

使用document.execCommand

先选中文字后点击按钮更改选中文字状态

html 复制代码
<!--点击的按钮不能为div,目前确认button可用-->
<button @click="f">操作</button>

常用代码片段

替换选中文字的内容

js 复制代码
function f() {
  const selectDom = document.getSelection().focusNode.parentElement // 获取包裹文字的元素dom
  selectDom.contentEditable = String(true) // 开启元素可编辑状态,document.execCommand需要
  document.execCommand('insertText', false, '***') // document.execCommand只能操纵可编辑内容区域的元素
  selectDom.contentEditable = String(false) // 重置编辑状态
}

更改选中文字的颜色,失去选中状态还保留颜色值

js 复制代码
function f() {
  const selectDom = document.getSelection().focusNode.parentElement
  selectDom.contentEditable = String(true)
  document.execCommand('foreColor', false, 'yellow')
  selectDom.contentEditable = String(false)
}
相关推荐
漂流瓶jz2 小时前
总结CSS组件化演进之路:命名规范/CSS Modules/CSS in JS/原子化CSS
前端·javascript·css
踩着两条虫2 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB2 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
即使再小的船也能远航3 小时前
【Python】安装
开发语言·python
Irissgwe3 小时前
类与对象(三)
开发语言·c++·类和对象·友元
steven~~~3 小时前
为什么mq报错
javascript
雪度娃娃4 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++
萌新小码农‍4 小时前
python装饰器
开发语言·前端·python
KK溜了溜了4 小时前
Python从入门到精通
服务器·开发语言·python
故事和你915 小时前
洛谷-【图论2-1】树5
开发语言·数据结构·c++·算法·动态规划·图论