anchor.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * 锚点插件,为UEditor提供插入锚点支持
  3. * @file
  4. * @since 1.2.6.1
  5. */
  6. UE.plugin.register("anchor", function() {
  7. return {
  8. bindEvents: {
  9. ready: function() {
  10. utils.cssRule(
  11. "anchor",
  12. ".anchorclass{background: url('" +
  13. this.options.themePath +
  14. this.options.theme +
  15. "/images/anchor.gif') no-repeat scroll left center transparent;cursor: auto;display: inline-block;height: 16px;width: 15px;}",
  16. this.document
  17. );
  18. }
  19. },
  20. outputRule: function(root) {
  21. utils.each(root.getNodesByTagName("img"), function(a) {
  22. var val;
  23. if ((val = a.getAttr("anchorname"))) {
  24. a.tagName = "a";
  25. a.setAttr({
  26. anchorname: "",
  27. name: val,
  28. class: ""
  29. });
  30. }
  31. });
  32. },
  33. inputRule: function(root) {
  34. utils.each(root.getNodesByTagName("a"), function(a) {
  35. var val;
  36. if ((val = a.getAttr("name")) && !a.getAttr("href")) {
  37. //过滤掉word冗余标签
  38. //_Toc\d+有可能勿命中
  39. if (/^\_Toc\d+$/.test(val)) {
  40. a.parentNode.removeChild(a);
  41. return;
  42. }
  43. a.tagName = "img";
  44. a.setAttr({
  45. anchorname: a.getAttr("name"),
  46. class: "anchorclass"
  47. });
  48. a.setAttr("name");
  49. }
  50. });
  51. },
  52. commands: {
  53. /**
  54. * 插入锚点
  55. * @command anchor
  56. * @method execCommand
  57. * @param { String } cmd 命令字符串
  58. * @param { String } name 锚点名称字符串
  59. * @example
  60. * ```javascript
  61. * //editor 是编辑器实例
  62. * editor.execCommand('anchor', 'anchor1');
  63. * ```
  64. */
  65. anchor: {
  66. execCommand: function(cmd, name) {
  67. var range = this.selection.getRange(),
  68. img = range.getClosedNode();
  69. if (img && img.getAttribute("anchorname")) {
  70. if (name) {
  71. img.setAttribute("anchorname", name);
  72. } else {
  73. range.setStartBefore(img).setCursor();
  74. domUtils.remove(img);
  75. }
  76. } else {
  77. if (name) {
  78. //只在选区的开始插入
  79. var anchor = this.document.createElement("img");
  80. range.collapse(true);
  81. domUtils.setAttributes(anchor, {
  82. anchorname: name,
  83. class: "anchorclass"
  84. });
  85. range
  86. .insertNode(anchor)
  87. .setStartAfter(anchor)
  88. .setCursor(false, true);
  89. }
  90. }
  91. }
  92. }
  93. }
  94. };
  95. });