我正在尝试获取 HTML 页面上的选择文本。
我使用下面的代码,并且window.getSelection()
文本区域接缝在 Firefox 中不起作用,
但在 Google Chrome 中运行良好。
- 我使用的是 Firefox 24 和 chrome 27。
这是一个示例:http://jsfiddle.net/AVLCY/ 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 错误 https://bugzilla.mozilla.org/show_bug.cgi?id=85686.
正如中所解释的这个答案 https://stackoverflow.com/a/10596963/2624466,解决方法是使用selectionStart
and selectionEnd
反而。
这是一个可以正常工作的修改示例:
http://jsfiddle.net/AVLCY/1/ http://jsfiddle.net/AVLCY/1/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)