0

您好,我希望我具有获取所选文本段落的功能。

这是获取所选文本的当前段落的功能

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);

}

如何在网页中获取所选文本的下一个上一段。如果我有功能来获取上面的当前段落。(我想使用 nextSibling 但我不知道在上面的代码中实现它)你能帮我吗?

-谢谢你-

4

1 回答 1

1

您可以使用 previousSibling 和 nextSibling 来获取参数。

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);
  }
}
于 2010-12-02T07:00:34.490 回答