[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=""
  }
}
相关推荐
疯子****7 分钟前
【无标题】
前端·clawdbot
RichardLau_Cx32 分钟前
【保姆级实操】MediaPipe SDK/API 前端项目接入指南(Web版,可直接复制代码)
前端·vue·react·webassembly·mediapipe·手部追踪·前端计算机视觉
不爱写程序的东方不败41 分钟前
APP接口测试流程实战Posman+Fiddler
前端·测试工具·fiddler
晚霞的不甘2 小时前
Flutter for OpenHarmony构建全功能视差侧滑菜单系统:从动效设计到多页面导航的完整实践
前端·学习·flutter·microsoft·前端框架·交互
黎子越2 小时前
python相关练习
java·前端·python
北极糊的狐2 小时前
若依项目vue前端启动键入npm run dev 报错:不是内部或外部命令,也不是可运行的程序或批处理文件。
前端·javascript·vue.js
XRJ040618xrj2 小时前
Nginx下构建PC站点
服务器·前端·nginx
We་ct2 小时前
LeetCode 289. 生命游戏:题解+优化,从基础到原地最优
前端·算法·leetcode·矩阵·typescript
有诺千金3 小时前
VUE3入门很简单(4)---组件通信(props)
前端·javascript·vue.js
2501_944711433 小时前
Vue-路由懒加载与组件懒加载
前端·javascript·vue.js