我想在HTML页面上获取选择文本。
我使用下面的代码,和 window.getSelection()
在textarea接缝不适用于Firefox,
但在谷歌浏览器中工作正常。
- 我使用的是firefox 24和chrome 27。
这是一个示例: http://jsfiddle.net/AVLCY/
HTML:
<div>Text in div</div>
<textarea>Hello textarea</textarea>
<div id='debug'></div>
JS:
$(document).on('mouseup','body',function(){
$("#debug").html("You select '" + getSelectionText() + "'");
});
function getSelectionText() {
if (window.getSelection) {
try {
// return "" in firefox
return window.getSelection().toString();
} catch (e) {
console.log('Cant get selection text')
}
}
// For IE
if (document.selection && document.selection.type != "Control") {
return document.selection.createRange().text;
}
}