Make Only Some Text Trigger Events in Actionscript
I have a block of text I am dynamically generating. It is about two sentences or so long, and only some of the words in the two sentences need to be able to trigger an event. For example, if I had "The cow jumped over the moon", I would like to make it so "开发者_Python百科cow" could be hovered over and have something pop up. After playing with TextField
some, it seems like it is not possible to do that there. Is it possible using some other construct (or hack)? If so, how?
Yes it can be done:
Use
getCharIndexAtPoint
to get the index of the character below the cursorFrom this index, expand (check the characters to the left and right and stop when you reach a delimiter - space, coma, etc.) to get the word under the cursor
Finally display your message based on the word you just found.
Here's some sample code. I didn't check if it compiles, but that should give you the general idea:
var fullText = textField.text;
var index = textField.getCharIndexAtPoint(cursorLoc);
var delimiters = " \n\r\t,?;!"; // Add a full list of delimiters here
var left = "";
var right = "";
for (var i = index - 1; i >= 0; i--) {
var c = fullText.charAt(i);
if (delimiters.indexOf(c) >= 0) break;
left = c + left;
}
for (var i = index + 1; i < fullText.length; i++) {
var c = fullText.charAt(i);
if (delimiters.indexOf(c) >= 0) break;
right = right + c;
}
var word = left + fullText.charAt(index) + right;
精彩评论