Character offset in an Internet Explorer TextRange

后端 未结 4 998
醉话见心
醉话见心 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:20

    You can iterate through the body element's TextRange.text property using String.substring() to compare against the TextRange for which you want the character offset.

    function charOffset(textRange, parentTextRange)
     { var parentTxt = parentTextRange.text;
       var txt       = textRange.text;
       var parentLen = parentTxt.length;
    
       for(int i=0; i < parentLen ; ++i) 
        { if (parentTxt.substring(i, txt.length+i) == txt) 
           { var originalPosition = textRange.getBookmark();
    
             //moves back one and searches backwards for same text
             textRange.moveStart("character",-1);
             var foundOther = textRange.findText(textRange.text,-parentLen,1);
    
             //if no others were found return offset
             if (!foundOther) return i;
    
             //returns to original position to try next offset
             else textRange.moveToBookmark(originalPosition);
           }
        }
    
       return -1;
     }
    

    [Reference for findText()]

提交回复
热议问题