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)
}
相关推荐
csbysj2020几秒前
Eclipse 视图(View)详解
开发语言
Embrace9245 分钟前
钉钉工作台内嵌应用=》调用钉钉对话框
前端·javascript·钉钉
zhangzeyuaaa10 分钟前
# Python 抽象类(Abstract Class)
开发语言·python
墨^O^10 分钟前
并发控制策略与分布式数据重排:锁机制、Redis 分片与 Spark Shuffle 简析
java·开发语言·c++·学习·spark
不被定义的~wolf12 分钟前
qt小游戏——坦克大作战
开发语言·qt
周不凢12 分钟前
elementui 表格行选择:通过 toggleRowSelection 方法控制表格行的选中状态
前端·javascript·elementui
一晌小贪欢16 分钟前
Web 自动化指南:如何用 Python 和 Selenium 解放双手
开发语言·前端·图像处理·python·自动化·python办公
云浪17 分钟前
认识 Service Worker
前端·javascript
问水っ18 分钟前
Qt Creator快速入门 第三版 第7章 Qt对象模型与容器类
开发语言·qt
方也_arkling20 分钟前
【Vue-Day11】props的使用
前端·javascript·vue.js