plugin.js 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. const options = {
  2. paragraph_open: '_p',
  3. bullet_list_open: '_ul',
  4. ordered_list_open: '_ol',
  5. hr: '_hr',
  6. link_open: '_a',
  7. blockquote_open: '_blockquote',
  8. table_open: '_table',
  9. thead_open: '_thead',
  10. tr_open: '_tr',
  11. th_open: '_th',
  12. td_open: '_td'
  13. };
  14. export function addCustomClassPlugin(md) {
  15. md.renderer.rules.heading_open = (tokens, idx, options, env, self) => {
  16. const token = tokens[idx];
  17. // console.log(token)
  18. // 判断当前标签是否为 h1
  19. if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(token.tag)) {
  20. // 给 h1 标签添加 class 属性
  21. token.attrJoin('class', `_${token.tag}`);
  22. }
  23. return self.renderToken(tokens, idx, options);
  24. };
  25. Object.keys(options).forEach((key) => {
  26. const className = options[key];
  27. md.renderer.rules[key] = (tokens, idx, options, env, self) => {
  28. tokens[idx].attrPush(['class', className]);
  29. return self.renderToken(tokens, idx, options);
  30. };
  31. });
  32. }