开发者

javascript string clicked position

开发者 https://www.devze.com 2023-01-04 12:08 出处:网络
If I have a string in a div <div id=\"article\"> lots of text goes here <strong> it\'s really interesting</strong>

If I have a string in a div

<div id="article">
 lots of text goes here
<strong> it's really interesting</strong>
and it's free to read
</div>

if a user double click or single click on a particular word, is there a way to determine the position/index of the character clicked?

If that cannot be done, how about determining how many space character there are before the c开发者_开发技巧licked position. So if I click on the word 'goes' in the above example, it returns 3 because there are three spaces before the word goes which is clicked.

Thank You very much for your time.


The ugly hack solution to such a problem involves programming converting the characters into event capturing objects.

For instance

<div id="article">
<span>lots </span><span>of </span><span>text</span>...
</div>

Now this can be done programmatically. You can grab whatever the current content of a div and convert it to something like the formatting above. Then attach event handlers to the contained spans which count the number of spans preceding it in the same container.


a way to determine the position/index of the character clicked

Well, first I need to use a fixed width size font like Courier. Then, I'd create two span with only a char each. With those two, I should be able to know the width of a char (beware padding and margin) and its height. Then, you need to know your upper left coordinates for your div whose id is 'article' and capture click event with event.x and event.y.

After that,

var line = (event.x - divLeft) / charHeight; 
var column = (event.y - divTop) / charWidth;
0

精彩评论

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

关注公众号