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)
}
相关推荐
摇滚侠1 分钟前
@Autowired 和 @Resource 的区别
java·开发语言
Wy_编程10 分钟前
go语言中的结构体
开发语言·后端·golang
SeaTunnel17 分钟前
(八)收官篇 | 数据平台最后一公里:数据集成开发设计与上线治理实战
java·大数据·开发语言·白鲸开源
大卡片1 小时前
C++的基础知识点
开发语言·c++
你很易烊千玺1 小时前
日常练习-数组 字符串常用的场景
前端·javascript·字符串·数组
郑同学的笔记2 小时前
【Qt教程29】Qt5和Qt6版本对比
开发语言·qt
基德爆肝c语言2 小时前
Qt 主窗口全家桶:菜单栏、工具栏、状态栏与对话框完全指南
开发语言·qt
存在的五月雨2 小时前
Vue3项目一些语法
前端·javascript·react.js
大家的林语冰3 小时前
Node 2026 发布,JS 三大新功能上线,最后一个奇偶版本
前端·javascript·node.js