2010-12-02 5 views
0

こんにちは私は選択されたテキストの段落を取得する機能が必要です。JavaScriptがウェブページの選択されたテキストの次の前の段落を取得する

これは

function getSelected() { 
    var userSelection; 
    if (window.getSelection) { 
     selection = window.getSelection(); 
    } else if (document.selection) { 
     selection = document.selection.createRange(); 
    } 
    var parent = selection.anchorNode; 
    parent = parent.parentNode; 
    alert(parent.innerHTML); 

} 

選択したテキストの現在の段落を取得する機能がどのように私は、Webページで選択したテキストの次の-前の段落を得ることができます。私は上記の現在の段落を取得する機能がある場合。 (私はnextSiblingを使用すると思いますが、上のコードで実装することはわかりません) 私を助けることができますか?

はあなたがパラメータを取得するためのpreviousSiblingとnextSiblingを使用することができますyou-が

答えて

0

を-thank。

HTML:

<p> This is 1st paragraph</p> 
<p> This is 2nd paragraph</p> 
<p> This is 3rd paragraph</p> 
<a href="javascript:void(0)" onclick="getSelected(-1)">Prev</a> 
<a href="javascript:void(0)" onclick="getSelected(1)">Next</a> 

Javascriptを:私は以前に単語を取得し、選択したテキストの次の場合

function getSelected(direction) { 
    var userSelection; 
    if (window.getSelection) { 
     selection = window.getSelection(); 
    } else if (document.selection) { 
     selection = document.selection.createRange(); 
    } 
    var parent = selection.anchorNode; 
    parent = parent.parentNode; 
    if(direction == -1){ 
    var prevEle = parent.previousSibling; 
    while(prevEle.nodeType!=1){ 
     prevEle = prevEle.previousSibling; 
    } 
    alert(prevEle.innerHTML); 
    }else { 
    var nextEle = parent.nextSibling ; 
    while(nextEle.nodeType!=1){ 
     nextEle = nextEle.nextSibling; 
    } 
    alert(nextEle.innerHTML); 
    } 
} 
+0

ことが可能です? – user495688

+0

これは、selectionとTextRangeオブジェクトに 'anchorNode'プロパティがないIEでは動作しません。 –

+0

この関数を使って別の段落にある単語を取得することは可能でしょうか? – user495688

関連する問題