JavaScript获取选中文本的兼容写法
作者:半夏时间:2026-10-27 20:06:29浏览:76
本文介绍如何在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;
} 作者最新文章
JavaScript闭包与类(Class)的区别及适用场景对比
2026-11-05 15:48:57
JavaScript入门要学ES6吗?let与箭头函数等新特性解析
2026-11-05 14:49:16
JavaScript 8种数据类型详解:基本类型与引用类型的区别
2026-11-05 14:25:15
怎么在JavaScript中使用async/await优化Ajax异步流程
2026-11-05 13:56:15
JavaScript replace回调函数实现动态正则替换逻辑
2026-11-05 13:52:13
