如何确定单击文本节点中的字符? [英] How to determine character in textnode that was clicked on?

查看:112
本文介绍了如何确定单击文本节点中的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以设置一个事件监听器,以便在HTML文档中的某个位置发生鼠标点击时告诉我。但如果点击发生在某些文本上,我需要知道点击发生的文本中的哪个字符。有没有办法这样做?

I can set up an event listener to tell me when a mouse click occurred at some place in an HTML document. But if the click occurred on some text, I need to know which character in the text the click occurred over. Is there a way to do this?

我可以想到一些非常讨厌的解决方案。例如,对于文档中的每个单个字符,我可以将其包含在具有自己的事件的单独元素中。或者,由于我可以知道点击发生了哪个文本节点,我可以使用clientWidth执行某种计算(基本上几乎像模拟文本的渲染)来确定点击发生的角色。

I can think of some really obnoxious solutions. For instance, for every single character in the document I could wrap it in a separate element with its own event. Or, since I can tell which textnode the click occurred in, I could perform some kind of calculation (basically almost like simulating rendering of the text) perhaps using clientWidth, to determine which character the click occurred in.

确实有一些更容易的东西?

Surely there must be something easier?

推荐答案

一旦捕获了鼠标事件,在元素中分为两个独立的跨度。查看每个跨度的偏移量,以确定事件发生在哪里。现在将该范围分成两个并再次进行比较。重复一次,直到有一个单一字符的坐标包含鼠标点击的坐标。由于这本质上是一个二进制搜索,这个整个过程将会相当快速,而且跨度的总数比较低。一旦找到了这个角色,跨度可以解散,所有的文本都返回原来的元素。

Once the mouse event is captured, split the text in the element into two separate spans. Look at the offset of each span to determine which the event occurred in. Now split that span in two and compare again. Repeat until you have a span that has a single character whose coordinates contain the coordinates of the mouse click. Since this is essentially a binary search this whole process will be fairly quick, and the total number of span low compared to the alternative. Once the character has been found, the spans can be dissolved and all the text returned to the original element.

这篇关于如何确定单击文本节点中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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