小程序富文本

<template>

<rich-text :nodes="nodes"></rich-text>

</template>

<script>

  import homeHelper from '@/store/home-helper.js'

  import parseHtml from "../../common/html-parser.js"

  import uniIcons from "@/components/uni-icons/uni-icons.vue"

  import uniGoodsNav from '@/components/uni-goods-nav/uni-goods-nav.vue'

  export default {

  props:["id"],

  components: {uniIcons,uniGoodsNav},

  data() {

  return {

adImgs: ['../../static/adv/home-bosom.jpg'],

nodes: []

 },

  created() {

  },

  onLoad(options) {


homeHelper.getProjectById(options.id).then(result=>{

let tempArr = [];

let arr = parseHtml(this.formatRichText(result.desc));

arr.forEach(item=>{

  tempArr.push(item);

});

this.nodes = tempArr;

})

  },

  methods:{

  formatRichText (html) { //控制小程序中图片大小

      let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){

          match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');

          match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');

          match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');

          return match;

      });

      newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){

          match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');

          return match;

      });

      newContent = newContent.replace(/<br[^>]*\/>/gi, '');

      newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');

      return newContent;

  }

  }

  }

</script>


html-parser.js

==========================================

/*

* HTML5 Parser By Sam Blowes

*

* Designed for HTML5 documents

*

* Original code by John Resig (ejohn.org)

* http://ejohn.org/blog/pure-javascript-html-parser/

* Original code by Erik Arvidsson, Mozilla Public License

* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js

*

* ----------------------------------------------------------------------------

* License

* ----------------------------------------------------------------------------

*

* This code is triple licensed using Apache Software License 2.0,

* Mozilla Public License or GNU Public License

*

* ////////////////////////////////////////////////////////////////////////////

*

* Licensed under the Apache License, Version 2.0 (the "License"); you may not

* use this file except in compliance with the License.  You may obtain a copy

* of the License at http://www.apache.org/licenses/LICENSE-2.0

*

* ////////////////////////////////////////////////////////////////////////////

*

* The contents of this file are subject to the Mozilla Public License

* Version 1.1 (the "License"); you may not use this file except in

* compliance with the License. You may obtain a copy of the License at

* http://www.mozilla.org/MPL/

*

* Software distributed under the License is distributed on an "AS IS"

* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the

* License for the specific language governing rights and limitations

* under the License.

*

* The Original Code is Simple HTML Parser.

*

* The Initial Developer of the Original Code is Erik Arvidsson.

* Portions created by Erik Arvidssson are Copyright (C) 2004. All Rights

* Reserved.

*

* ////////////////////////////////////////////////////////////////////////////

*

* This program is free software; you can redistribute it and/or

* modify it under the terms of the GNU General Public License

* as published by the Free Software Foundation; either version 2

* of the License, or (at your option) any later version.

*

* This program is distributed in the hope that it will be useful,

* but WITHOUT ANY WARRANTY; without even the implied warranty of

* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

* GNU General Public License for more details.

*

* You should have received a copy of the GNU General Public License

* along with this program; if not, write to the Free Software

* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

*

* ----------------------------------------------------------------------------

* Usage

* ----------------------------------------------------------------------------

*

* // Use like so:

* HTMLParser(htmlString, {

*    start: function(tag, attrs, unary) {},

*    end: function(tag) {},

*    chars: function(text) {},

*    comment: function(text) {}

* });

*

* // or to get an XML string:

* HTMLtoXML(htmlString);

*

* // or to get an XML DOM Document

* HTMLtoDOM(htmlString);

*

* // or to inject into an existing document/DOM node

* HTMLtoDOM(htmlString, document);

* HTMLtoDOM(htmlString, document.body);

*

*/

// Regular Expressions for parsing tags and attributes

var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;

var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;

var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; // Empty Elements - HTML 5

var empty = makeMap('area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr'); // Block Elements - HTML 5

// fixed by xxx 将 ins 标签从块级名单中移除

var block = makeMap('a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video'); // Inline Elements - HTML 5

var inline = makeMap('abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'); // Elements that you can, intentionally, leave open

// (and which close themselves)

var closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'); // Attributes that have their values filled in disabled="disabled"

var fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'); // Special Elements (can contain anything)

var special = makeMap('script,style');

function HTMLParser(html, handler) {

  var index;

  var chars;

  var match;

  var stack = [];

  var last = html;

  stack.last = function () {

    return this[this.length - 1];

  };

  while (html) {

    chars = true; // Make sure we're not in a script or style element

    if (!stack.last() || !special[stack.last()]) {

      // Comment

      if (html.indexOf('<!--') == 0) {

        index = html.indexOf('-->');

        if (index >= 0) {

          if (handler.comment) {

            handler.comment(html.substring(4, index));

          }

          html = html.substring(index + 3);

          chars = false;

        } // end tag

      } else if (html.indexOf('</') == 0) {

        match = html.match(endTag);

        if (match) {

          html = html.substring(match[0].length);

          match[0].replace(endTag, parseEndTag);

          chars = false;

        } // start tag

      } else if (html.indexOf('<') == 0) {

        match = html.match(startTag);

        if (match) {

          html = html.substring(match[0].length);

          match[0].replace(startTag, parseStartTag);

          chars = false;

        }

      }

      if (chars) {

        index = html.indexOf('<');

        var text = index < 0 ? html : html.substring(0, index);

        html = index < 0 ? '' : html.substring(index);

        if (handler.chars) {

          handler.chars(text);

        }

      }

    } else {

      html = html.replace(new RegExp('([\\s\\S]*?)<\/' + stack.last() + '[^>]*>'), function (all, text) {

        text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, '$1$2');

        if (handler.chars) {

          handler.chars(text);

        }

        return '';

      });

      parseEndTag('', stack.last());

    }

    if (html == last) {

      throw 'Parse Error: ' + html;

    }

    last = html;

  } // Clean up any remaining tags

  parseEndTag();

  function parseStartTag(tag, tagName, rest, unary) {

    tagName = tagName.toLowerCase();

    if (block[tagName]) {

      while (stack.last() && inline[stack.last()]) {

        parseEndTag('', stack.last());

      }

    }

    if (closeSelf[tagName] && stack.last() == tagName) {

      parseEndTag('', tagName);

    }

    unary = empty[tagName] || !!unary;

    if (!unary) {

      stack.push(tagName);

    }

    if (handler.start) {

      var attrs = [];

      rest.replace(attr, function (match, name) {

        var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : '';

        attrs.push({

          name: name,

          value: value,

          escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') // "

        });

      });

      if (handler.start) {

        handler.start(tagName, attrs, unary);

      }

    }

  }

  function parseEndTag(tag, tagName) {

    // If no tag name is provided, clean shop

    if (!tagName) {

      var pos = 0;

    } // Find the closest opened tag of the same type

    else {

        for (var pos = stack.length - 1; pos >= 0; pos--) {

          if (stack[pos] == tagName) {

            break;

          }

        }

      }

    if (pos >= 0) {

      // Close all the open elements, up the stack

      for (var i = stack.length - 1; i >= pos; i--) {

        if (handler.end) {

          handler.end(stack[i]);

        }

      } // Remove the open elements from the stack

      stack.length = pos;

    }

  }

}

function makeMap(str) {

  var obj = {};

  var items = str.split(',');

  for (var i = 0; i < items.length; i++) {

    obj[items[i]] = true;

  }

  return obj;

}

function removeDOCTYPE(html) {

  return html.replace(/<\?xml.*\?>\n/, '').replace(/<!doctype.*>\n/, '').replace(/<!DOCTYPE.*>\n/, '');

}

function parseAttrs(attrs) {

  return attrs.reduce(function (pre, attr) {

    var value = attr.value;

    var name = attr.name;

    if (pre[name]) {

pre[name] = pre[name] + " " + value;

    } else {

pre[name] = value;

    }

    return pre;

  }, {});

}

function parseHtml(html) {

  html = removeDOCTYPE(html);

  var stacks = [];

  var results = {

    node: 'root',

    children: []

  };

  HTMLParser(html, {

    start: function start(tag, attrs, unary) {

      var node = {

        name: tag

      };

      if (attrs.length !== 0) {

        node.attrs = parseAttrs(attrs);

      }

      if (unary) {

        var parent = stacks[0] || results;

        if (!parent.children) {

          parent.children = [];

        }

        parent.children.push(node);

      } else {

        stacks.unshift(node);

      }

    },

    end: function end(tag) {

      var node = stacks.shift();

      if (node.name !== tag) console.error('invalid state: mismatch end tag');

      if (stacks.length === 0) {

        results.children.push(node);

      } else {

        var parent = stacks[0];

        if (!parent.children) {

          parent.children = [];

        }

        parent.children.push(node);

      }

    },

    chars: function chars(text) {

      var node = {

        type: 'text',

        text: text

      };

      if (stacks.length === 0) {

        results.children.push(node);

      } else {

        var parent = stacks[0];

        if (!parent.children) {

          parent.children = [];

        }

        parent.children.push(node);

      }

    },

    comment: function comment(text) {

      var node = {

        node: 'comment',

        text: text

      };

      var parent = stacks[0];

      if (!parent.children) {

        parent.children = [];

      }

      parent.children.push(node);

    }

  });

  return results.children;

}

export default parseHtml;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 226,197评论 6 524
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 97,254评论 3 410
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 173,718评论 0 370
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 61,801评论 1 305
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 70,732评论 6 404
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 54,200评论 1 318
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,389评论 3 433
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 41,484评论 0 282
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,024评论 1 328
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,013评论 3 352
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,125评论 1 359
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 37,698评论 5 353
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,407评论 3 342
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,795评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,996评论 1 278
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 50,724评论 3 384
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,150评论 2 368