你好,我希望我有功能来获取所选文本的段落。
这是获取所选文本的当前段落的功能
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但我不知道在上面的代码中实现它) 你能救我吗?
- 谢谢你 -
答案 0 :(得分:0)
您可以使用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);
}
}