[Vue3 + TS + Vite] 获取网页选中内容的字符串格式或HTML格式

获取网页选中内容的字符串格式

typescript 复制代码
let selected_text_by_mouse: any

// 获取选中的文字
const mouse_selected_text=(event:MouseEvent)=>{
  const selection = window.getSelection();
  if(selection && selection.rangeCount > 0){
    const content = selection.toString();
    selected_text_by_mouse = content
  }
  else{
    selected_text_by_mouse=""
  }
}

获取网页选中内容的HTML格式
(无法获取选中文字最外面的HTML标签)
例如:

html 复制代码
<p>一<span>段文</span>字</p>

选中"一段文字"之后,得到的是:

html 复制代码
一<span>段文</span>字

而不是:

html 复制代码
<p>一<span>段文</span>字</p>
typescript 复制代码
let selected_text_by_mouse: any

// 获取选中的文字
const mouse_selected_text=(event:MouseEvent)=>{
  const selection = window.getSelection();
  if(selection && selection.rangeCount > 0){
    const range = selection.getRangeAt(0)
    const clonedFragment = range.cloneContents()
    // 创建一个临时容器以容纳克隆的片段
    const innerTmpContainer = document.createElement('div')
    innerTmpContainer.appendChild(clonedFragment)
    
    const contentHtmlString = innerTmpContainer.innerHTML
    // 清除临时容器(可选)
    innerTmpContainer.remove()

    const content = contentHtmlString
    selected_text_by_mouse = content
  }
  else{
    selected_text_by_mouse=""
  }
}
相关推荐
crary,记忆1 分钟前
MFE微前端基础版:Angular + Module Federation + webpack + 路由(Route way)完整示例
前端·学习·webpack·angular
williamdsy4 分钟前
【Vue PDF】Vue PDF 组件初始不加载 pdfUrl 问题分析与修复
前端·javascript·vue.js·pdf
南囝coding44 分钟前
这个 361K Star 的项目,一定要收藏!
前端·后端·github
我不吃饼干44 分钟前
我给掘金写了一个给用户加标签的功能
前端·javascript·cursor
羚羊角uou1 小时前
【C++】模拟实现map和set
java·前端·c++
90后的晨仔1 小时前
ArkTS 与 Swift 闭包的对比分析
前端·harmonyos
小小小小宇2 小时前
前端用户行为监控
前端
亦舒.2 小时前
网盘直链解析网页版
html
步行cgn2 小时前
Vue 事件修饰符详解
前端·javascript·vue.js
vvilkim2 小时前
Flutter 状态管理基础:深入理解 setState 和 InheritedWidget
前端·javascript·flutter