Character offset in an Internet Explorer TextRange

后端 未结 4 1000
醉话见心
醉话见心 2020-12-11 07:42

As far as I can tell there\'s no simple way of retrieving a character offset from a TextRange object in Internet Explorer. The W3C Range object has a node, and the offset in

4条回答
  •  暖寄归人
    2020-12-11 08:02

    I use a method based on this caret position trick:

    // Assume r is a range:
    var offsetFromBody = Math.abs( r.moveEnd('character', -1000000) );
    

    Since moveEnd returns the number of characters actually moved, offset should now be the offset from the start of the document. This works fine for testing primitive caret movement, but for expanded selections and for getting the exact node that holds the range anchor you'll need something more complex:

    // where paramter r is a range:
    function getRangeOffsetIE( r ) {
      var end = Math.abs( r.duplicate().moveEnd('character', -1000000) );
      // find the anchor element's offset
      var range = r.duplicate();
      r.collapse( false );
      var parentElm = range.parentElement();
      var children = parentElm.getElementsByTagName('*');
      for (var i = children.length - 1; i >= 0; i--) {
        range.moveToElementText( children[i] );
        if ( range.inRange(r) ) {
          parentElm = children[i];
          break;
        }
      }
      range.moveToElementText( parentElm );
      return end - Math.abs( range.moveStart('character', -1000000) );
    }
    

    This should return the correct caret text offset. Of course, if you know the target node already, or are able to provide a context, then you can skip the whole looping search mess.

提交回复
热议问题