index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. menu - header
  3. */
  4. import $ from '../../util/dom-core.js'
  5. import DropList from '../droplist.js'
  6. // 构造函数
  7. function Head(editor) {
  8. this.editor = editor
  9. this.$elem = $('<div class="lsiten-e-menu"><i class="lsiten-e-icon-header"></i></div>')
  10. this.type = 'droplist'
  11. // 当前是否 active 状态
  12. this._active = false
  13. // 初始化 droplist
  14. this.droplist = new DropList(this, {
  15. width: 100,
  16. $title: $('<p>设置标题</p>'),
  17. type: 'list', // droplist 以列表形式展示
  18. list: [
  19. { $elem: $('<h1>标题</h1>'), value: '<h1>' },
  20. { $elem: $('<h4>副标题</h4>'), value: '<h4>' },
  21. { $elem: $('<h2>标题1</h2>'), value: '<h2>' },
  22. { $elem: $('<h3>标题2</h3>'), value: '<h3>' },
  23. { $elem: $('<h5>标题3</h5>'), value: '<h5>' },
  24. { $elem: $('<p>正文</p>'), value: '<div class="para-text">' }
  25. ],
  26. onClick: (value) => {
  27. // 注意 this 是指向当前的 Head 对象
  28. this._command(value)
  29. }
  30. })
  31. }
  32. // 原型
  33. Head.prototype = {
  34. constructor: Head,
  35. // 执行命令
  36. _command: function (value) {
  37. const editor = this.editor
  38. const $selectionElem = editor.selection.getSelectionContainerElem()
  39. if (editor.$textElem.equal($selectionElem)) {
  40. // 不能选中多行来设置标题,否则会出现问题
  41. // 例如选中的是 <p>xxx</p><p>yyy</p> 来设置标题,设置之后会成为 <h1>xxx<br>yyy</h1> 不符合预期
  42. return
  43. }
  44. editor.cmd.do('formatBlock', value)
  45. },
  46. // 试图改变 active 状态
  47. tryChangeActive: function (e) {
  48. const editor = this.editor
  49. const $elem = this.$elem
  50. const reg = /^h/i
  51. const cmdValue = editor.cmd.queryCommandValue('formatBlock')
  52. if (reg.test(cmdValue)) {
  53. this._active = true
  54. $elem.addClass('lsiten-e-active')
  55. } else {
  56. this._active = false
  57. $elem.removeClass('lsiten-e-active')
  58. }
  59. }
  60. }
  61. export default Head