从Xpath获取文本并突出显示它

时间:2013-10-30 11:20:26

标签: javascript xpath

我正在尝试构建一个E pub Reader。我能够突出显示用户选择的文本,我正在获取该特定选定文本的x路径。之后,我正在尝试构建一个以x path作为参数并通过更改背景颜色显示用户所选文本的函数。但它不起作用。

代码: -

function uiWebview_restoreSelection() {
var selectionDetails = "/HTML[1]/BODY[1]/DIV[1]/text()[1]|910|/HTML[1]/BODY[1]/DIV[1]/text()[1]|930";
//alert("selectionDetails"+selectionDetails);
if (selectionDetails != null) {
    selectionDetails = selectionDetails.split(/\|/g);
    alert("selectionDetails" + selectionDetails);
    if (typeof window.getSelection != 'undefined') {
        var selection = window.getSelection();
        selection.removeAllRanges();
        var range = document.createRange();
        var selectionDetails0 = selectionDetails[0];
        alert("selectionDetails0" + selectionDetails0);
        selectionDetails0 = selectionDetails0.replace(/\//g, "/h:");
        selectionDetails0 = selectionDetails0.replace("h:t", "t");
        alert("selectionDetails0" + selectionDetails0);
        var selectionDetails2 = selectionDetails[2];
        alert("selectionDetails2" + selectionDetails2);
        selectionDetails2 = selectionDetails2.replace(/\//g, "/h:");
        selectionDetails2 = selectionDetails2.replace("h:t", "t");
        alert("selectionDetails2" + selectionDetails2);
        range.setStart(document.evaluate(selectionDetails0, document, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[1]));
        range.setEnd(document.evaluate(selectionDetails2, document, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[3]));
        document.designMode = "on";
        var newSpanMark = document.createElement("span");
        document.execCommand("HiliteColor", false, "red");
        range.insertNode(newSpanMark);
        document.designMode = "off";

    }
}
}

请为上述问题提出建议。

先谢谢

0 个答案:

没有答案