js 匹配 img标签 增加 style样式

给img标签增加 style样式:

1、如果img 标签没有style 就先添加style标签

2、添加标签后统一再添加style样式

   function  imgTagAddStyle (htmlstr) {
      // 正则匹配所有img标签
      // var regex0 = new RegExp("(i?)(<img)([^>]+>)","gmi");
      // 正则匹配不含style="" 或 style='' 的img标签
      // eslint-disable-next-line no-useless-escape
      var regex1 = new RegExp("(i?)(<img)(?!(.*?style=['"](.*)['"])[^>]+>)", 'gmi')
      // 给不含style="" 或 style='' 的img标签加上style=""
      htmlstr = htmlstr.replace(regex1, '$2 style=""$3')
      console.log('增加style=""后的html字符串:' + htmlstr)
      // 正则匹配含有style的img标签
      // eslint-disable-next-line no-useless-escape
      var regex2 = new RegExp("(i?)(<img.*?style=['"])([^>]+>)", 'gmi')
      // 在img标签的style里面增加css样式(这里增加的样式:display:block;max-100%;height:auto;border:5px solid red;)
      htmlstr = htmlstr.replace(regex2, '$2max-100%;height:auto;$3')
      console.log('在img标签的style里面增加样式后的html字符串:' + htmlstr)
      return htmlstr
    }
微信公众号:jingfeng18 免费学习领取最新的前端学习资源
原文地址:https://www.cnblogs.com/qianduanshiping/p/11826847.html