[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=""
  }
}
相关推荐
星栈2 分钟前
我在浏览器里试了试 PhotoCraft|Rust + WASM 修图,是玩具还是生产力?
前端
雨中飘荡的记忆1 小时前
淘宝搜不到的东西,能不能去全世界找?一个程序员的创业尝试
前端·设计
kyriewen1 小时前
我让 4 位 AI 面试官打分,同一个我差了 40 分
前端·面试·程序员
htzyl2062 小时前
Vue3中watch的deep默认值:reactive与ref为什么相反
前端·vue.js
用户112936112193 小时前
没写样式为什么还找我要 wxss?uni-app 这个 ENOENT 坑多数人误判了
前端·微信小程序·uni-app
用户553665935263 小时前
从零做一个全国山峰与线路库:山野抽签的初衷、架构与踩坑
前端
夕水3 小时前
用 SolidJS 复刻 DeepSeek Chat —— 顺便把 ew-solid-ui 拷打了一遍
前端·javascript
qq_274475153 小时前
第 17 篇:ES6 语法速览:解构赋值、展开运算符、模板字符串、对象简写
前端·ecmascript·es6
凯程序猿1号5 小时前
Web墨卡托EPSG3857瓦片行列号XYZ与经纬度双向换算及地面分辨率推导
前端·电脑
qq_274475155 小时前
第 21 篇:Proxy 代理与 Reflect:数据劫持基础,Vue 响应式底层原理前置
前端·javascript·vue.js