网页中js如何获取用户选中的内容?
微wx笑
2025-05-11【前端开发】
4
0
0关键字:
如何获取用户选中的内容?这里有一个问题:window.getSelection() 方法不能获取 input 标签中选中的内容,主要是因为 window.getSelection() 方法的局限性。这个方法适用于获取可
如何获取用户选中的内容?
这里有一个问题:
问题原因
input 元素的特殊性:input 元素的文本内容由
value
属性管理,而非 DOM 子节点。window.getSelection()
只能获取可视化的 DOM 选中区域,而 input 的文本不是以常规 DOM 子节点形式存在的。Range 对象的限制:你创建的 Range 对象只能操作普通 DOM 节点,无法访问 input 内部的文本选区。
如何获取 input 标签中选中的内容?注意,我不知道用户是选择的网页内容还是 input标签中的内容
以下代码提取统一的解决方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | function getSelectionDetails() { // 获取当前活动元素(焦点所在元素) const activeElement = document.activeElement; // 检查活动元素是否为 input 或 textarea if ( activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA' ) ) { // 处理 input/textarea 中的选中文本 const start = activeElement.selectionStart; const end = activeElement.selectionEnd; if (start !== null && end !== null && start !== end) { const txt = activeElement.value.substring(start, end); return { type: 'input' , element: activeElement, text: txt, html:txt, start:start, end:end }; } } // 处理普通网页元素中的选中文本 const selectionObj = window.getSelection(); if (selectionObj && selectionObj.rangeCount > 0) { rangeObj = selectionObj.getRangeAt(0); var docFragment = rangeObj.cloneContents(); //然后将docFragment渲染出来,获取其innerHTML即可。 var testDiv = document.createElement( "div" ); testDiv.appendChild(docFragment); selectHtml = testDiv.innerHTML; const selectedText = selectionObj.toString(); if (selectedText) { return { type: 'page' , text: selectedText, html: selectHtml, range: rangeObj, selection:selectionObj }; } } return null ; // 没有选中内容 } |
// 使用示例
1 2 3 4 5 6 7 | document.addEventListener( 'mouseup' , () => { const selection = getSelectionDetails(); if (selection) { console.log(`选中类型: ${selection.type}`); console.log(`选中内容: ${selection.text}`); } }); |
为什么要增加 element、start、end、range、selection 这些返回值属性呢?
看下面的代码:
1 2 3 4 5 6 7 8 9 | if (selection){ if ( 'input' === selection.type){ selection.element.focus(); selection.element.select(selection.start, selection.end); } else { selection.selection.empty(); selection.selection.addRange(selection.range); } } |
如果因为某种原因,你的脚本导致选中的内容取消选中状态了,
那么可以通过以上代码还原选区。
本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/front/2025-05-11/2068.html
下一篇:返回列表