[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=""
  }
}
相关推荐
恋猫de小郭9 分钟前
Flutter A2UI 的正确用法,怎么把 AI 和动态 UI 结合有效生产
android·前端·flutter
程序员-珍18 分钟前
安卓开发:同名 styles.xml 在不同分支/文件夹的合并规则
android·xml·前端
Ashley的成长之路24 分钟前
前端性能优化实战手册·第5篇(最终篇):性能监控与 CI/CD 集成
前端·ci/cd·性能优化
chemddd35 分钟前
第四节课:前端
前端
雪芽蓝域zzs38 分钟前
(一)Vue3+JS+Vite+pnpm 仿若依后台 从零搭建
前端
常宇佳1 小时前
vue3 $refs使用方法
前端·vue.js·typescript
zhanghaha13141 小时前
HTML系列教程:4_什么是 HTML 元素(零基础超详细讲解)
前端·算法·html
AI 编程助手GPT2 小时前
VS Code 1.133 实战:Claude 可免 GitHub 登录,HTML 保存后自动刷新
前端·html·github
灯澜忆梦2 小时前
【基于GO的Web开发3】gin框架_HTML渲染
前端·golang·gin
小徐_23339 小时前
wot-ui-cli 1.1.0 发布:支持 OpenCode、Antigravity,wot-ui 图标迁移不再靠猜
前端