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)
}
相关推荐
Rabitebla6 分钟前
C++ 入门基础:从 C 到 C++ 的第一步
c语言·开发语言·c++
西魏陶渊明7 分钟前
解决异步挑战:Reactor Context 实现响应式上下文传递
开发语言·python
小则又沐风a12 分钟前
C++内存管理 C++模板
开发语言·c++
不会写DN12 分钟前
如何给 Go 语言的 TCP 聊天服务加上 ACK 可靠送达机制
开发语言·tcp/ip·golang
小李云雾16 分钟前
FastAPI 后端开发:文件上传 + 表单提交
开发语言·python·lua·postman·fastapi
llm大模型算法工程师weng23 分钟前
Python敏感词检测方案详解
开发语言·python·c#
fengci.24 分钟前
php反序列化(复习)(第二章)
android·开发语言·学习·php
ZHENGZJM25 分钟前
后端基石:Go 项目初始化与数据库模型设计
开发语言·数据库·golang
拾贰_C26 分钟前
【Claude Code | bash | install】安装Claude Code
开发语言·bash
苏瞳儿27 分钟前
前端/后端-配置跨域
前端·javascript·node.js·vue