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 分钟前
Electron开发
前端·javascript·electron
紫金修道6 小时前
【DeepAgent】概述
开发语言·数据库·python
Via_Neo6 小时前
JAVA中以2为底的对数表示方式
java·开发语言
书到用时方恨少!6 小时前
Python multiprocessing 使用指南:突破 GIL 束缚的并行计算利器
开发语言·python·并行·多进程
cch89186 小时前
PHP五大后台框架横向对比
开发语言·php
天真萌泪7 小时前
JS逆向自用
开发语言·javascript·ecmascript
野生技术架构师7 小时前
一线大厂Java面试八股文全栈通关手册(含源码级详解)
java·开发语言·面试
柳杉7 小时前
震惊!字符串还能这么玩!
前端·javascript
Q一件事8 小时前
R语言制图-相关性及关系网络图
开发语言·r语言
坊钰8 小时前
Java 死锁问题及其解决方案
java·开发语言·数据库