Get a range's start and end offset's relative to its parent container

前端 未结 4 1908
独厮守ぢ
独厮守ぢ 2020-11-22 05:19

Suppose I have this HTML element:

Hello everyone! This is my home page

Bye!

4条回答
  •  有刺的猬
    2020-11-22 05:40

    This solution works by counting length of text content of previous siblings walking back up to the parent container. It probably doesn't cover all edge cases, although it does handle nested tags of any depth, but it's a good, simple place to start from if you have a similar need.

      calculateTotalOffset(node, offset) {
        let total = offset
        let curNode = node
    
        while (curNode.id != 'parent') {
          if(curNode.previousSibling) {
            total += curNode.previousSibling.textContent.length
    
            curNode = curNode.previousSibling
          } else {
            curNode = curNode.parentElement
          }
        }
    
       return total
     }
    
     // after selection
    
    let start = calculateTotalOffset(range.startContainer, range.startOffset)
    let end = calculateTotalOffset(range.endContainer, range.endOffset)
    

提交回复
热议问题