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)
}
相关推荐
Ashley_Amanda16 分钟前
JavaScript 中 JSON 的处理方法
前端·javascript·json
历程里程碑20 分钟前
hot 206
java·开发语言·数据结构·c++·python·算法·排序算法
csbysj202033 分钟前
菜单(Menu)
开发语言
yong99901 小时前
基于MATLAB的随机振动界面设计与功率谱密度分析实现
开发语言·matlab
超级种码1 小时前
Java:JavaAgent技术(java.instrument和java.attach)
java·开发语言·python
天天向上10241 小时前
go 配置热更新
开发语言·后端·golang
晨晖22 小时前
顺序查找:c语言
c语言·开发语言·算法
wadesir2 小时前
C++非对称加密实战指南(从零开始掌握RSA加密算法)
开发语言·c++
编程修仙2 小时前
第三篇 Vue路由
前端·javascript·vue.js
a程序小傲3 小时前
阿里Java面试被问:.Java 8中Stream API的常用操作和性能考量
开发语言·windows·python