JavaScript获取选中文本的兼容写法

作者:半夏

时间:2026-10-27

浏览:75

本文介绍如何在JavaScript中兼容获取用户选中的文本。通过判断window.getSelection、document.getSelection及document.selection的存在性,实现跨浏览器兼容的代码逻辑,确保在不同浏览器环境下都能正确返回选中内容。

文章目录

JavaScript获取选中文本的兼容写法

代码如下:

 
function getSelectedText() { //此函数代码源自:http://www.codetoad.com/javascript_get_selected_text.asp
var txt = "";
if (window.getSelection) {
txt = window.getSelection();
} else if (window.document.getSelection) {
txt = window.document.getSelection();
} else if (window.document.selection) {
txt = window.document.selection.createRange().text;
} 
return txt;
} 

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章