Determine the position index of a character within an HTML element when clicked

后端 未结 4 1622
误落风尘
误落风尘 2020-12-09 09:49

I have an HTML element with only visible text inside. This example is a

element, but it could be a ,

4条回答
  •  遥遥无期
    2020-12-09 10:47

    In many cases, a possible solution can be to add zero-width space character (U+200B) between each char of the content of the tag. Then using javascript window.getSelection().focusOffset + some simple computations does the job.

    Sample html code (including zero-width space characters):

    T​h​i​s​ ​i​s​ ​a​ ​s​i​m​p​l​e​ ​e​x​a​m​p​l​e​.

    Sample javascript code:

    
    

    Seems to work widely, even on internet explorer!

    jsFidle: http://jsfiddle.net/by1a9pfm/

提交回复
热议问题