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)
}
相关推荐
overmind4 分钟前
oeasy Python 114 在列表指定位置插入insert
开发语言·python
github.com/starRTC10 分钟前
Claude Code中英文系列教程34:再谈Skills
开发语言·c#·ai编程
毕设源码-赖学姐15 分钟前
【开题答辩全过程】以 基于Java的外卖点餐网站为例,包含答辩的问题和答案
java·开发语言
蜡笔羊驼34 分钟前
LALIC环境安装过程
开发语言·python·深度学习
codeJinger39 分钟前
【Python】基础知识
开发语言·python
css趣多多1 小时前
Vue 响应式无限递归问题总结
前端·javascript·vue.js
lsx2024061 小时前
JavaScript Math(算数)详解
开发语言
csbysj20201 小时前
Debian Docker 安装指南
开发语言
ShineWinsu1 小时前
对于模拟实现C++list类的详细解析—上
开发语言·数据结构·c++·算法·面试·stl·list
Mr YiRan1 小时前
C++语言类中各个重要函数原理
java·开发语言·c++