HarmonyOS 鸿蒙Next 对字符串中指定文字高亮
HarmonyOS 鸿蒙Next 对字符串中指定文字高亮
```typescript function splitAndKeep(info, search) { let result = []; let lastIndex = 0; while (true) { const index = info.indexOf(search, lastIndex); if (index === -1) { // 当没有找到更多搜索文本时,将剩余部分添加到结果数组 result.push(info.slice(lastIndex)); break; } else { // 找到搜索文本时,先将搜索文本前的部分添加到结果数组 result.push(info.slice(lastIndex, index)); // 然后将搜索文本本身添加到结果数组 result.push(info.slice(index, index + search.length)); // 更新下次查找的起始位置 lastIndex = index + search.length; } } return result; }
@Entry @Component struct Index { @State info: string = ‘字符串中指定文字高亮,字符串中指定文字高亮,今天心情还好,字符串中指定文字高亮,字符串中指定文字高不亮,字符串中指定文字不高亮,字符串高亮高亮中指定文字高亮,字符串中指定文字高亮。’ @State search: string = ‘高亮’ //需要高亮的内容 @State arr: string[] = []
aboutToAppear(){ this.arr = splitAndKeep(this.info, this.search) console.info(’====arr’,JSON.stringify(this.arr)); }
build() { Column({ space: 20 }) { ForEach(this.arr,(item,index)=>{ if(item == this.search){ Span(item).fontColor(Color.Red).fontSize(30).onClick(()=>{ console.info(’====click item–>’,item) console.info(’====click index–>’,index) }) }else{ Span(item).fontColor(Color.Black).fontSize(30) } }) } } } ```
更多关于HarmonyOS 鸿蒙Next 对字符串中指定文字高亮的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于HarmonyOS 鸿蒙Next 对字符串中指定文字高亮的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS(鸿蒙Next)中,对字符串中指定文字进行高亮显示,可以通过使用Text
组件的Span
功能来实现。Span
允许你对文本中的特定部分进行样式设置,包括字体颜色、背景色、字体大小等。
例如,假设你有一个字符串str = "这是一个示例文本,用于演示高亮功能。"
,你想要高亮其中的“示例”两个字。你可以通过以下代码实现:
import { Text, Span } from '@ohos/text';
let str = "这是一个示例文本,用于演示高亮功能。";
let startIndex = str.indexOf("示例");
let endIndex = startIndex + "示例".length;
let highlightedText = new Text();
highlightedText.addSpan(new Span(startIndex, endIndex, { color: '#FF0000' }));
highlightedText.text = str;
在这个例子中,Span
对象用于指定需要高亮的文本范围(从startIndex
到endIndex
),并设置其颜色为红色(#FF0000
)。然后,将这个Span
应用到Text
对象中,最终显示时,“示例”两个字将以红色高亮显示。
这种方式可以灵活地对字符串中的任意部分进行高亮处理,适用于各种文本显示场景。