获取网页选中内容的字符串格式
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 = contentHtmlStringselected_text_by_mouse = content}else{selected_text_by_mouse=""}
}