11

我有这个小提琴:http: //jsfiddle.net/Uddaa/

目前它的作用是,当您单击文本时,它会在文本到该点时发出警报。我该怎么做才能使 html 达到这一点而不仅仅是文本?

JavaScript:

$(".content").on("click", function () {
    getBefore();
});

function getBefore() {
    var sel = document.getSelection();
    var off = sel.anchorOffset;
    var ran = sel.getRangeAt(0);
    ran.setStart($(".content").get(0), 0);
    alert(ran.toString());
}

HTML:

<div class="content">
    <p><b>Click</b> anywhere <u>within <em>the</em> text</u> to to see the code up to that point.</p>
</div>
4

2 回答 2

11

ran.cloneContents().childNodes[1].innerHTML给你完整的html。

请参阅jsfiddle或代码片段。

document.querySelector(".content").addEventListener("click", getHtmlBeforeThis);

function getHtmlBeforeThis(evt) {
  const origin = evt.target.closest(".content");
  if (origin) {
    const selection = document.getSelection();
    const offset = selection.anchorOffset;
    const range = selection.getRangeAt(0);
    range.setStart(origin, 0);
    const upToClickedHtml = range.cloneContents().childNodes[1].innerHTML;
    range.setEnd(origin, 0);
    console.clear();
    console.log(upToClickedHtml);
  }
}
<div class="content">
    <p><b>Click</b> anywhere <u>within <em>the</em> text</u> to to see the code up to that point.</p>
</div>

于 2013-11-08T14:35:44.693 回答
1

您可以使用Rangy库来执行此操作:

rangy.getSelection().toHtml()

示例小提琴

于 2013-11-08T14:27:10.983 回答