原生js--搜索输入框匹配文字高亮

/**
   * 搜索出的列表中文字的颜色高亮
   * @param prope 需要高亮的属性
  */
  highLightText = (prope) => {
    // searchval是搜索的关键字,list是原始的数据
    const {searchval,list} = this.state
    // 最终输出的数据
    let matchVal = [];
    list.forEach((item, index) => {
      let isMatch = true, // 是否匹配
          rawVal = item[prope] // 进行匹配的原始字符串
          matchVal[index] = [] // 初始化数据
      while (isMatch) {
        // 对关键字的位置进行匹配
        let pos = rawVal.indexOf(searchval)
        if (pos === -1) { // 没有匹配到关键字
          isMatch = false
          matchVal[index].push({ [prope]: rawVal.substring(0, rawVal.length),name: item.name })
        } else {
          // 当前匹配的位置+关键字的长度
          let matchEnd = pos + searchval.length
          // 没有匹配到的关键字
          matchVal[index].push({ [prope]: rawVal.substring(0, pos),name: item.name })
          // 匹配到的关键字
          matchVal[index].push({ [prope]: rawVal.substring(pos, matchEnd), matched: true,name: item.name })
          // 将匹配到的文字进行删除,将原始数据进行重新筛选
          rawVal = rawVal.substring(matchEnd, rawVal.length)
          // 当匹配的长度到了末尾,将不再进行匹配
          if (!rawVal && rawVal.length < 1) {
            isMatch = false
          }
        }
	  }
	})
    return matchVal
  }
// react中的render中的代码:
render() {
    const {list, operaList, isShowContent,loading} = this.state
    return (
      <div className="box">
        operaList.map((item,index) => {
          return(
            <div key={list[index].id} onClick={() => this.handleClick(list[index].id)}>
              <span>{list[index].name}</span>
              {
                item.map((subItem,subIndex) => {
                  return (
                    <span key={index + subIndex} style={{color: subItem.matched ? '#9b7235' : '#666'}}>
                      {subItem.id}
                    </span>
                  )
                })
              }
            </div>
          )
        })
      }
      </div>
    )
  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值