[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=""
  }
}
相关推荐
想睡好几秒前
css文本属性
前端·css
qianmoQ2 分钟前
第三章:组件开发实战 - 第五节 - Tailwind CSS 响应式导航栏实现
前端·css
zhoupenghui16815 分钟前
golang时间相关函数总结
服务器·前端·golang·time
White graces29 分钟前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea
庸俗今天不摸鱼30 分钟前
Canvas进阶-4、边界检测(流光,鼠标拖尾)
开发语言·前端·javascript·计算机外设
bubusa~>_<1 小时前
解决npm install 出现error,比如:ERR_SSL_CIPHER_OPERATION_FAILED
前端·npm·node.js
流烟默2 小时前
vue和微信小程序处理markdown格式数据
前端·vue.js·微信小程序
梨落秋溪、2 小时前
输入框元素覆盖冲突
java·服务器·前端
菲力蒲LY2 小时前
vue 手写分页
前端·javascript·vue.js
天下皆白_唯我独黑3 小时前
npm 安装扩展遇到证书失效解决方案
前端·npm·node.js