开发者

Getting text at clicked location in an HTML element

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜