anchor.js 3.2 KB

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