Retrieving DOM textnode position

后端 未结 6 2088
萌比男神i
萌比男神i 2020-12-30 01:14

Is it possible to retrieve the geometric position (i.e. top/left offsets from either the parent element, the page, etc) of a text node?

6条回答
  •  悲哀的现实
    2020-12-30 01:51

    Today you can via Range.getBoundingClientRect(). IE9+

    // Get your text node
    const el = document.querySelector('strong')
    const textNode = el.firstChild;
    
    // Get coordinates via Range
    const range = document.createRange();
    range.selectNode(textNode);
    const coordinates = range.getBoundingClientRect()
    
    console.log(coordinates);
    /* Demo CSS, ignore, highlights box coordinates */ body{max-width:300px}strong{position:relative}strong,strong:before{border:solid 1px red}strong:before{content:'';position:absolute;right:100%;bottom:100%;width:100vw;height:100vh;pointer-events:none}
    The red lines will show you the coordinates bounding box of the selected textnode.

提交回复
热议问题