Calculating text selection offsets in nest elements in Javascript

前端 未结 5 1886
无人及你
无人及你 2021-01-05 14:58

The Problem

I am trying to figure out the offset of a selection from a particular node with javascript.

Say I have the following HTML

5条回答
  •  走了就别回头了
    2021-01-05 15:56

    What does this offset actually mean? An offset within the innerHTML of an element is going to be extremely fragile: any insertion of a new node or change to an attribute of an element preceding the point in the document the offset represents is going to make that offset invalid.

    I strongly recommend using the browser's built-in support for this in the form of DOM Range. You can get hold of a range representing the current selection as follows:

    var range = window.getSelection().getRangeAt(0);
    

    If you're going to be manipulating the DOM based on this offset that you want, you're best off doing so using nodes instead of string representations of those nodes.

提交回复
热议问题