[Vue3 + TS + Vite] 获取网页选中内容的字符串格式或HTML格式

获取网页选中内容的字符串格式

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标签)
例如:

<p><span>段文</span></p>

选中“一段文字”之后,得到的是:

<span>段文</span>

而不是:

<p><span>段文</span></p>
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=""
  }
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-13 04:14:03       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-13 04:14:03       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-13 04:14:03       45 阅读
  4. Python语言-面向对象

    2024-07-13 04:14:03       55 阅读

热门阅读

  1. 【python】IPython的使用技巧

    2024-07-13 04:14:03       22 阅读
  2. C++中struct与class区别,C与C++中struct区别

    2024-07-13 04:14:03       27 阅读
  3. HTTPS和HTTP有哪些区别

    2024-07-13 04:14:03       18 阅读
  4. Qt开发 | Qt创建线程 | Qt并发-QtConcurrent

    2024-07-13 04:14:03       13 阅读
  5. UI图标库推荐网站

    2024-07-13 04:14:03       18 阅读