2012-09-25 40 views
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 

我不知道怎麼去選擇的文本。任何人都可以幫助我呢?非常感謝!

+0

Ref。選擇(MDN)https://developer.mozilla.org/en-US/docs/DOM/Selection – prashanth

回答

2

window.getSelection()返回Selection對象。

如果你想獲得選定的文本不假思索更多,你應該做的:

window.getSelection().toString() 

但是如果你的選擇可能是比較複雜的,你應該閱讀MDN documentation。如果用戶選擇所有的句子「款第二段」,那麼最簡單的方式是行不通的

<div class="text_speech"> 
    <p>First paragraph</p> 
    <p>Second paragraph <strong>big</strong></p> 
</div> 

例如,用戶可以用多個標籤選擇文本。

0

嘗試:

console.log(textTest.toString());