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)
}
相关推荐
泯泷23 分钟前
第二章:你的第一个Lit组件 - 从零到"Hello, World"
前端·javascript·web components
geovindu42 分钟前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
geovindu1 小时前
python:Lasso
开发语言·后端·python·算法
多加点辣也没关系2 小时前
JavaScript|第42章:安全与最佳实践
开发语言·javascript·安全
3095566662 小时前
股票数据落库前的去重与主键设计:一次 SQLite 写入实录
java·开发语言·jvm·数据库·redis·python·sqlite
泯泷2 小时前
第三章:lit-html的威力 - 精通声明式模板
前端·javascript·web components
利威尔xu3 小时前
2026-11-19-Go反射为什么慢面试
开发语言·面试·golang
bai2733 小时前
npm 在 cmd 里能跑,Node 的 spawn 一调就 EINVAL:Windows 上 .cmd 的六种调法实测
javascript·后端
山楂树の3 小时前
Python 函数:参数、作用域、Lambda 与类型注解
开发语言·python
旖旎夜光3 小时前
【C 语言】(一)(下)指针进阶:const、二级指针、函数指针与指针题
c语言·开发语言·笔记·学习