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)
}
相关推荐
Xiu Yan13 分钟前
Java 转 C++ 系列:函数模板
java·开发语言·c++
froginwe1123 分钟前
如何使用 AppML
开发语言
格林威29 分钟前
工业相机“心跳”监测脚本(C# 版) 支持海康 / Basler / 堡盟工业相机
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·视觉检测
我能坚持多久31 分钟前
String类常用接口的实现
c语言·开发语言·c++
夜宵饽饽33 分钟前
Agent文件系统检索核心:Grep和Glob工具
javascript·github
花间相见35 分钟前
【大模型微调与部署03】—— ms-swift-3.12 命令行参数(训练、推理、对齐、量化、部署全参数)
开发语言·ios·swift
默 语38 分钟前
Java的“后路“:不是退场,而是换了一种活法
java·开发语言·python
t***54439 分钟前
Orwell Dev-C++和Embarcadero Dev-C++哪个更稳定
开发语言·c++
黑牛儿41 分钟前
同样是 PHP-FPM 调优,别人能支撑 1000 + 并发,你却还在报 502?
开发语言·php
wjs202441 分钟前
R 数据类型
开发语言