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;
} 
作者最新文章