我一直在努力解决这个问题:

我有一个包含html的字符串,我正在使用正则表达式来获取标记之间的字符。然后我试图将TextFormat应用于这些字符。

问题是我正在使用textfield的“htmltext”属性而不是它的“text”属性(因为我不希望可见的html标记)。因此,当我应用TextFormat时,从正则表达式返回的字符索引不正确。

以下是一些示例代码,说明了问题:

var txt:String = "<b>Sample</b> string with bold text";

var tf:TextField = new TextField();
addChild(tf);
tf.htmlText = txt;

var format:TextFormat = new TextFormat();
format.bold = true;

var regExp:RegExp = /<b>(.*?)<\/b>/g;
var match:Object = regExp.exec(txt);
while (match != null) {
    tf.setTextFormat(format, match.index, match.index + match[0].length);
    match = regExp.exec(txt);
}
.

这给了我:

样本字符串具有粗体文本”

而不是所需的:

样本字符串,粗体”

因为match[0].length是七个字符太长,因为HTML标签是<b></b>

我该怎么办?谢谢!

有帮助吗?

解决方案

Using TextField.htmlText, <b> tags should give bold text, without any need for TextFormat.bold or regexp, provided you embed the right fonts (or use device fonts).

But, I know there is sometimes issues with the HTML support in TextFields in combination with font handling, and perhaps your actual situation is more complex than the example with bold text. In that case I would recommend using StyleSheet formatting instead of the regexp/TextFormat combo. Besides the problem with offset mismatch that you have encountered, I believe that combining the two different approaches to text formatting - HTML and TextFormat - runs the risk of giving other problems, while using HTML text and StyleSheet are meant to be used together.

I started writing an example of using StyleSheet/htmlText, but since <b> should work anyway, without styling, it got a bit weird, so I scratched it. But let me know if you need example code.

其他提示

tf.setTextFormat(format, match.index, match.index + match[1].length); 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top