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)
}
相关推荐
前端小巷子8 分钟前
Webpack 5模块联邦
前端·javascript·面试
晓得迷路了12 分钟前
栗子前端技术周刊第 91 期 - 新版 React Compiler 文档、2025 HTML 状态调查、Bun v1.2.19...
前端·javascript·react.js
江城开朗的豌豆24 分钟前
前端路由傻傻分不清?route和router的区别,看完这篇别再搞混了!
前端·javascript·vue.js
枫叶丹433 分钟前
【Qt开发】信号与槽(二)-> 信号和槽的使用
开发语言·qt
Vertira1 小时前
python 阿里云 安装 dashscope的简介、安装
开发语言·python
LBJ辉2 小时前
2. Webpack 高级配置
前端·javascript·webpack
hqxstudying3 小时前
Java异常处理
java·开发语言·安全·异常
wjs20246 小时前
状态模式(State Pattern)
开发语言
我命由我123456 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
liulilittle6 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap