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)
}
相关推荐
sg_knight1 分钟前
设计模式实战:策略模式(Strategy)
java·开发语言·python·设计模式·重构·架构·策略模式
麦麦鸡腿堡2 分钟前
JavaWeb_SpringBootWeb,HTTP协议,Tomcat快速入门
java·开发语言
码云数智-园园4 分钟前
前端跨域全解析:核心原理、解决方案选型与实战指南
开发语言
qq_417695055 分钟前
内存对齐与缓存友好设计
开发语言·c++·算法
2301_816651225 分钟前
实时系统下的C++编程
开发语言·c++·算法
2401_831824966 分钟前
C++与Python混合编程实战
开发语言·c++·算法
飞Link9 分钟前
告别 ROS 的臃肿:用 ZeroMQ 构建极速具身智能分布式大脑(附 Python 实战)
开发语言·分布式·python
qq_2113874712 分钟前
基于LangGraph多agent
开发语言·前端·javascript·agent·langgraph
※※冰馨※※12 分钟前
【QT】TortoiseGit配 SSH 克隆 Codeup
开发语言·c++·windows