[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=""
  }
}
相关推荐
Hilaku1 天前
为什么在 2026 年,MPA(多页面应用)正在悄悄复辟?
前端·javascript·程序员
幸福小宝1 天前
eslint和prettier
前端
anyup1 天前
终于在今天入选了 Gitee GVP,这真值得庆祝~
前端·uni-app·开源
幸福小宝1 天前
husky和lint-staged
前端
Slice_cy1 天前
Mint 自研框架设计与实现:从重复开发走向配置驱动(五)
前端·后端·架构
寒水馨1 天前
Windows下载、安装 Tailwind CSS-v4.3.3(附安装包tailwindcss-windows-x64.exe)
前端·css·前端开发·tailwind css·utility-first·css 框架·独立 cli
西楼_1 天前
一文读懂React19究竟更新了什么
前端
四眼肥鱼1 天前
【Nextjs】macos 系统运行报错:Error: Cannot find module '../lightningcss.darwin-x64.node'
前端·架构·前端框架
hoLzwEge1 天前
Unplugin Turbo Console:让你的 `console.log` 脱胎换骨
前端·前端框架
dota李天王1 天前
简单的 socket 实现
前端·javascript·websocket