Calculating text selection offsets in nest elements in Javascript

前端 未结 5 1889
无人及你
无人及你 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:43

    Just check if your selected element is a paragraph, and if not use something like Prototype's Element.up() method to select the first paragraph parent.

    For example:

    if(selected_element.nodeName != 'P') {
      parent_paragraph = $(selected_element).up('p');
    }
    

    Then just find the difference between the parent_paragraph's text offset and your selected_element's text offset.

提交回复
热议问题