Getting text at clicked location in an HTML element

拜拜、爱过 提交于 2019-12-11 01:39:39

问题


I have a div element containing some text. When the user clicks a word inside that div I'd like to highlight just that word.

In order to do this I need to know what character position in the text the click occurred at, so I can then locate nearby whitespace and insert some formatting around the word.

Finding out where the click occurred within the text is the trick here. Is that kind of thing possible?


回答1:


If your page is auto-generated, you might consider pre-processing the page by putting a <span class = 'word'> around every word in every selectable div. You might be able to this with javascript after the fact, and I think that would be your solution regardless, but pre-processing would make it easier.

The problem with relying on the absolute position of the word is that users can scale their fonts, which makes this task especially hard. By wrapping a span around every individual word, you can easily select which word was clicked by applying the click event to the span elements.



来源:https://stackoverflow.com/questions/2664271/getting-text-at-clicked-location-in-an-html-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!