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)
}
相关推荐
牛十二20 小时前
nacos2.4连接出错源码分析
java·linux·开发语言
|晴 天|20 小时前
Vue 3 实现实时通知系统:支持未读计数、红点提醒、一键已读
javascript·vue.js·ecmascript
小松加哲20 小时前
AspectJ编译期织入实战
java·开发语言
鲸渔20 小时前
【C++ 跳转语句】break、continue、goto 与 return
开发语言·c++·算法
大流星20 小时前
敲黑板!async/await应用原理
前端·javascript
喜欢吃燃面20 小时前
Linux 进程信号深度解析:从概念到产生机制
linux·开发语言·学习
AI玫瑰助手20 小时前
Python基础:字符串的常用内置方法(查找替换分割)
android·开发语言·python
Foreer黑爷20 小时前
Java并发工具箱:CountDownLatch与CyclicBarrier使用指南
java·开发语言·jvm
syker20 小时前
AIFerric v2.0 项目总结报告
c语言·开发语言·c++
qq_120840937120 小时前
Three.js 工程向:相机控制与交互手感调优(OrbitControls)
前端·javascript·orbitcontrols