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)
}
相关推荐
雪域迷影18 分钟前
C++ 11 中的move赋值运算符
开发语言·c++·move
jf加菲猫27 分钟前
第2章 Hello World
开发语言·c++·qt·ui
不爱吃糖的程序媛30 分钟前
Electron 智能文件分析器开发实战适配鸿蒙
前端·javascript·electron
flashlight_hi1 小时前
LeetCode 分类刷题:3217. 从链表中移除在数组中存在的节点
javascript·数据结构·leetcode·链表
Java追光着1 小时前
React Native 自建 JS Bundle OTA 更新系统:从零到一的完整实现与踩坑记录
javascript·react native·react.js
努力往上爬de蜗牛1 小时前
react native 运行问题和调试 --持续更新
javascript·react native·react.js
todoitbo1 小时前
Rust新手第一课:Mac环境搭建踩坑记录
开发语言·macos·rust
laplace01231 小时前
PyQt5 + Qt Designer配置指令
开发语言·qt
nvd112 小时前
Python 迭代器 (Iterator) vs. 生成器 (Generator)
开发语言·python