Javascript 如何获取突出显示的文本?
我试图从用户那里获取所选文本(用户高亮显示的高亮显示文本) 我有以下资料:Javascript 如何获取突出显示的文本?,javascript,jquery,Javascript,Jquery,我试图从用户那里获取所选文本(用户高亮显示的高亮显示文本) 我有以下资料: function getSelectedTexts(){ var t = ''; if(window.getSelection){ t = window.getSelection(); console.log('1'); }else if(document.getSelection){ t = document.getSelection(); console.log('2');
function getSelectedTexts(){
var t = '';
if(window.getSelection){
t = window.getSelection();
console.log('1');
}else if(document.getSelection){
t = document.getSelection();
console.log('2');
}else if(document.selection){
console.log('3');
t = document.selection.createRange().text;
}
return t;
}
$('.text_speech').live('click',function(e){
e.preventDefault();
var textTest='';
textTest=getSelectedTexts();
console.log(textTest);
})
我的控制台回来了
1
>Selection <------object
anchorNode: Text
anchorOffset: 2
baseNode: Text
baseOffset: 2
extentNode: Text
extentOffset: 1
focusNode: Text
focusOffset: 1
isCollapsed: false
rangeCount: 1
type: "Range"
__proto__: Selection
1
>选择尝试:
window.getSelection()
返回一个Selection
对象
如果您希望在不考虑更多内容的情况下获取所选文本,则应执行以下操作:
window.getSelection().toString()
但是如果你的选择可能更复杂,你应该阅读
例如,用户可能选择带有多个标记的文本:
第一段
第二段big
如果用户选择了所有句子“段落第二段big”,那么简单的方法将不起作用。Ref.Selection(MDN)
console.log(textTest.toString());