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)
}
相关推荐
htzyl2064 小时前
javaScript中,让你全面了解动态import()的四个真实用途,及与静态import的区别
前端·javascript
OpsEye4 小时前
新手别混淆!RPM 和 TPM,大模型调用的两个限流密码
javascript·ai编程
xurileidian5 小时前
第 22 篇 · 边玩边学Python · 双等号与 is 不是一回事
开发语言·python·spring
FRing035 小时前
for循环、while循环、Java高级语法、数组
java·开发语言·后端·算法
syf0611135 小时前
Java Math 类详解:常用数学运算方法全解析
java·开发语言
是main不是漫6 小时前
【双指针 | LeetCode11 盛最多水的容器】O(n²) 超时,O(n) 封神:这道“装水题“只差一个思路
开发语言·数据结构·c++·算法
polarisya6 小时前
vue搭建知识
前端·javascript·vue.js
geovindu7 小时前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
map_vis_3d7 小时前
百度地图控件一览:缩放、比例尺、定位、城市列表、地图类型和 3D 导航
前端·javascript·地图·百度地图
Hilaku7 小时前
国内前端面试最离谱的现象:笔试题考手写 Promise.all
前端·javascript·程序员