我正在使用以下函数来获取所选文本,它在所有主流浏览器中都运行良好但在版本9之前的IE中无法正常工作!
function getSelected() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
t = t.toString();
} else if (document.selection) {
t = document.selection.createRange();
t = t.text;
}
return t;
}
var txt = getSelected();
这里的问题是,在版本9之前的IE中,它不会在变量“txt”中存储任何文本
答案 0 :(得分:0)
DEMO: http://jsfiddle.net/ytJ35/
以下内容取自How to get selected html text with javascript?
这个javascript函数适用于IE7及以上版本:
function getSelected() {
var text = "";
if (window.getSelection
&& window.getSelection().toString()
&& $(window.getSelection()).attr('type') != "Caret") {
text = window.getSelection();
return text;
}
else if (document.getSelection
&& document.getSelection().toString()
&& $(document.getSelection()).attr('type') != "Caret") {
text = document.getSelection();
return text;
}
else {
var selection = document.selection && document.selection.createRange();
if (!(typeof selection === "undefined")
&& selection.text
&& selection.text.toString()) {
text = selection.text;
return text;
}
}
return false;
}
在chrome,IE10,IE6,IE7中测试