我正在尝试在HTML页面上获取选择文本。
我使用下面的代码,并且window.getSelection()
在textarea接缝上无法在Firefox中使用,但在Google Chrome中可以正常使用。
这是一个示例: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;
}
}
getSelection
由于此Firefox错误,它似乎不适用于在表单字段中选择的文本。
正如在解释这个答案,解决办法是使用selectionStart
和selectionEnd
替代。
这是一个正确运行的修改后的示例:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句