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 に答える