Das Front-End-JS realisiert den Inhaltsersatz des regulären Emoticon-Pakets und die Realisierung des Front-End-Emoticon-Pakets

Willkommen beim Click-to-Follow-Advanced-Leitfaden für Front-End-Interviews: Front-End nach oben – die umfassendste Zusammenfassung der Front-End-Wissenspunkte

Umsetzung von Emoticons

Idee: Gehen Sie den Textinhalt durch die globale Regularisierung, passen Sie das Text-Emoticon-Paket [hey ha] an und erstellen Sie ein div- oder img-Tag, um das Text-Emoticon-Paket durch den Adresslink unseres Emoticon-Pakets zu ersetzen.

// 创建文件emoticon.js
import lottie from "lottie-web"; // 动画方法

const emoticon = new Map([
  ['[大笑]', {
    
    
    name: 'daxiao',
    src: 'https://url-daxiao.json' // 表情包地址
  }]
 ]}

// 根据资源文件生成正则匹配规则
const regExpFn = () => {
    
    
  let ruleStr = '';
  emoticon.forEach((val, key) => {
    
    
    const text = key.replace(/\[|\]/g, function (w: any): any {
    
    
      if (w === '[') {
    
    
        return '\\['
      } else if (w === ']') {
    
    
        return '\\]'
      }
    })
    ruleStr += text + '|'
  })
  ruleStr = ruleStr.substr(0, ruleStr.length - 1)
  return new RegExp(ruleStr, 'g')
}

// 替换内容里的表情包
const emotiomReplace = (params = {
     
     }) => {
    
    
  const lottieWrap = {
    
    };
  const {
    
     content, id } = params
  const result = content.replace(regExpFn(), (world, index) => {
    
    
    const type = world, lookId = id + '-' + index;
    if (lottieWrap[lookId]) return false;
      const div = document.getElementById(lookId)
      if (div && !div.innerHTML) {
    
    
        const path = emoticon.get(div.getAttribute('type')).src
        lottieWrap[lookId] = lottie.loadAnimation({
    
    
          container: div,
          renderer: 'svg',
          loop: true,
          path
        })
      }
    return `<div style="display: inline-block; width: 20px; height: 20px; 
    margin: 0 1px; vertical-align: middle;" type="${
      
      type}" id="${
      
      lookId}"></div>`
  })
  return result;
}

export {
    
    
  emotiomReplace
}
verwenden
import {
    
     emotiomReplace } from './emoticon.js'
<span v-html="emotiomReplace(后端数据)"></span>

Guess you like

Origin blog.csdn.net/weixin_43624724/article/details/120185799