2017-02-10 11 views
1

のにもかかわらず、空の文字列を返します。selection.toStringは()私は、次のコードを使用してクリック上の要素のテキストを選択しようとしている選択範囲

var selection = window.getSelection(); 
var range = document.createRange(); 
range.selectNodeContents(element); 
selection.removeAllRanges(); 
selection.addRange(range); 

テキストが強調表示なっているが、空の文字列がコピーされますクリップボードはCtrl + Cを使用しています。selection.toString()をチェックすると空文字列も返します。なぜこれが起こっているのだろうか?

+0

私は範囲について少し知っているが、 'range.selectNodeContents(要素)を交換してみてください;' 'range.selectNode(要素)と;' 私はあなたのエラーを再作成し、これは私のためにそれを修正しました。例:https://jsfiddle.net/ShawnGrav/rd5rvu52/ –

答えて

2

フム、私はあなたのコードを見ていたし、試してみました:

var selection = window.getSelection(); 
var selectionText = selection.anchorNode.textContent 

と私が選択したテキストの内容を得ました。

EDIT:これはクリック機能でラップされているようです... 1秒。

$('<your selector goes here>').click(function(e) { 
    var selection = window.getSelection(); 
    var range = document.createRange(); 
    range.selectNodeContents(e.target); 
    selection.removeAllRanges(); 
    selection.addRange(range); 
    console.dir(selection.anchorNode.textContent); 
    //text content should display... 
    //now that the content is highlighted, you can copy it 
    document.execCommand('copy'); 

}) 
関連する問題