在HTML元素中的单击位置获取文本 [英] Getting text at clicked location in an HTML element

查看:116
本文介绍了在HTML元素中的单击位置获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些文本的div元素.当用户单击该div中的一个单词时,我只想突出显示该单词.

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?

推荐答案

如果页面是自动生成的,则可以考虑通过在每个可选div中的每个单词周围放置一个<span class = 'word'>来预处理页面.事后,您也许可以使用javascript做到这一点,并且我认为这将是您的解决方案,但是预处理将使其变得更容易.

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.

依赖于单词的绝对位置的问题是用户可以缩放其字体,这使这项任务特别困难.通过在每个单词周围加上一个跨度,可以通过将click事件应用于跨度元素来轻松地选择单击了哪个单词.

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.

这篇关于在HTML元素中的单击位置获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆