HarmonyOS 鸿蒙Next 对字符串中指定文字高亮

HarmonyOS 鸿蒙Next 对字符串中指定文字高亮

https://alliance-communityfile-drcn.dbankcdn.com/FileServer/getFile/cmtybbs/071/824/066/0260086000071824066.20240205111714.86922603696168835800798468015946:50001231000000:2800:7D55AF80C71109662A2D2ED9967742AB86A5CA3EC934F6602BE36CB5577EC3CC.png

```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

1 回复

更多关于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对象用于指定需要高亮的文本范围(从startIndexendIndex),并设置其颜色为红色(#FF0000)。然后,将这个Span应用到Text对象中,最终显示时,“示例”两个字将以红色高亮显示。

这种方式可以灵活地对字符串中的任意部分进行高亮处理,适用于各种文本显示场景。

回到顶部