-
Notifications
You must be signed in to change notification settings - Fork 79
/
main.js
2394 lines (2324 loc) · 97.5 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license Copyright (c) 2009-2013, xhEditor.com. All rights reserved.
* For licensing, see LGPL-LICENSE.txt or http://xheditor.com/license/lgpl.txt
*/
(function($, undefined){
if(!$.browser){
function uaMatch( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
var matched = uaMatch( navigator.userAgent );
var browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
$.browser = browser;
}
})(jQuery);
(function(XHEDITOR, $, undefined){
var agent=navigator.userAgent.toLowerCase();
var bMobile=/mobile/i.test(agent),
browser=$.browser,browerVer=parseFloat(browser.version),
isIE=browser.msie,
isIE11 = /trident\//i.test(agent) && (/rv:/i.test(agent) || /Netscape/i.test(agent.appName)),
isMozilla=browser.mozilla,
isWebkit=browser.webkit,
isOpera=browser.opera,
isChrome=browser.chrome,
bAir=agent.indexOf(' adobeair/')>-1;
var xCount=0,bShowPanel=false,bClickCancel=true,bShowModal=false,bCheckEscInit=false;
var _jPanel,_jShadow,_jCntLine,_jPanelButton;
var jModal,jModalShadow,layerShadow,jOverlay,jHideSelect,onModalRemove;
var editorRoot;
var getLang = XHEDITOR.getLang;
$('script[src*=xheditor]').each(function(){
var s=this.src;
if(s.match(/xheditor[^\/]*\.js/i)){editorRoot=s.replace(/[\?#].*$/, '').replace(/(^|[\/\\])[^\/]*$/, '$1');return false;}
});
if(isIE){
//ie6 缓存背景图片
try{document.execCommand('BackgroundImageCache', false, true );}
catch(e){}
//修正 jquery 1.6,1.7系列在IE6浏览器下造成width="auto"问题的修正
var jqueryVer=$.fn.jquery;
if(jqueryVer&&jqueryVer.match(/^1\.[67]/))$.attrHooks['width']=$.attrHooks['height']=null;
}
var specialKeys={ 27: 'esc', 9: 'tab', 32:'space', 13: 'enter', 8:'backspace', 145: 'scroll',
20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down',
112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12' };
var arrAlign=[{v:'justifyleft'},{v:'justifycenter'},{v:'justifyright'},{v:'justifyfull'}];
var arrList=[{v:'insertOrderedList'},{v:'insertUnorderedList'}];
var htmlPastetext='<div><label for="xhePastetextValue">{#PastetextTip}</label></div><div><textarea id="xhePastetextValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="{#dialogOk}" /></div>';
var htmlLink='<div><label for="xheLinkUrl">{#link.url}</label><input type="text" id="xheLinkUrl" value="http://" class="xheText" /></div><div><label for="xheLinkTarget">{#link.target}</label><select id="xheLinkTarget"><option selected="selected" value="">{#default}</option><option value="_blank">{#link.targetBlank}</option><option value="_self">{#link.targetSelf}</option><option value="_parent">{#link.targetParent}</option></select></div><div style="display:none"><label for="xheLinkText">{#link.linkText}</label><input type="text" id="xheLinkText" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="{#dialogOk}" /></div>';
var htmlAnchor='<div><label for="xheAnchorName">{#anchor.name}</label><input type="text" id="xheAnchorName" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="{#dialogOk}" /></div>';
var htmlImg='<div><label for="xheImgUrl">{#img.url}</label><input type="text" id="xheImgUrl" value="http://" class="xheText" /></div><div><div><label for="xheImgAlt">{#img.alt}</label><input type="text" id="xheImgAlt" /></div><div><label for="xheImgAlign">{#img.align}</label><select id="xheImgAlign"><option selected="selected" value="">{#default}</option><option value="left">{#img.alignLeft}</option><option value="right">{#img.alignRight}</option><option value="top">{#img.alignTop}</option><option value="middle">{#img.alignMiddle}</option><option value="baseline">{#img.alignBaseline}</option><option value="bottom">{#img.alignBottom}</option></select></div><div><label for="xheImgWidth">{#img.width}</label><input type="text" id="xheImgWidth" style="width:40px;" /> <label for="xheImgHeight">{#img.height}</label><input type="text" id="xheImgHeight" style="width:40px;" /></div><div><label for="xheImgBorder">{#img.border}</label><input type="text" id="xheImgBorder" style="width:40px;" /></div><div><label for="xheImgHspace">{#img.hspace}</label><input type="text" id="xheImgHspace" style="width:40px;" /> <label for="xheImgVspace">{#img.vspace}</label><input type="text" id="xheImgVspace" style="width:40px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="{#dialogOk}" /></div>';
var htmlFlash='<div><label for="xheFlashUrl">{#flash.url}</label><input type="text" id="xheFlashUrl" value="http://" class="xheText" /></div><div><label for="xheFlashWidth">{#flash.width}</label><input type="text" id="xheFlashWidth" style="width:40px;" value="480" /> <label for="xheFlashHeight">{#flash.height}</label><input type="text" id="xheFlashHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="{#dialogOk}" /></div>';
var htmlMedia='<div><label for="xheMediaUrl">{#media.url}</label><input type="text" id="xheMediaUrl" value="http://" class="xheText" /></div><div><label for="xheMediaWidth">{#media.width}</label><input type="text" id="xheMediaWidth" style="width:40px;" value="480" /> <label for="xheMediaHeight">{#media.height}</label><input type="text" id="xheMediaHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="{#dialogOk}" /></div>';
var htmlTable='<div><label for="xheTableRows">{#table.rows}</label><input type="text" id="xheTableRows" style="width:40px;" value="3" /> <label for="xheTableColumns">{#table.columns}</label><input type="text" id="xheTableColumns" style="width:40px;" value="2" /></div><div><label for="xheTableHeaders">{#table.headers}</label><select id="xheTableHeaders"><option selected="selected" value="">{#none}</option><option value="row">{#table.headersRow}</option><option value="col">{#table.headersCol}</option><option value="both">{#table.headersBoth}</option></select></div><div><label for="xheTableWidth">{#table.width}</label><input type="text" id="xheTableWidth" style="width:40px;" value="200" /> <label for="xheTableHeight">{#table.height}</label><input type="text" id="xheTableHeight" style="width:40px;" value="" /></div><div><label for="xheTableBorder">{#table.border}</label><input type="text" id="xheTableBorder" style="width:40px;" value="1" /></div><div><label for="xheTableCellSpacing">{#table.cellSpacing}</label><input type="text" id="xheTableCellSpacing" style="width:40px;" value="1" /> <label for="xheTableCellPadding">{#table.cellPadding}</label><input type="text" id="xheTableCellPadding" style="width:40px;" value="1" /></div><div><label for="xheTableAlign">{#table.align}</label><select id="xheTableAlign"><option selected="selected" value="">{#default}</option><option value="left">{#table.alignLeft}</option><option value="center">{#table.alignCenter}</option><option value="right">{#table.alignRight}</option></select></div><div><label for="xheTableCaption">{#table.caption}</label><input type="text" id="xheTableCaption" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="{#dialogOk}" /></div>';
var htmlAbout='<div style="font:12px Arial;width:245px;word-wrap:break-word;word-break:break-all;outline:none;" role="dialog" tabindex="-1"><p><span style="font-size:20px;color:#1997DF;">xhEditor</span><br />v@VERSION (build @BUILDDATE)</p><p>{#aboutXheditor}</p><p>Copyright © <a href="http://xheditor.com/" target="_blank">xhEditor.com</a>. All rights reserved.</p></div>';
var itemEmots={'default':{name:'{#default}',width:24,height:24,line:7,list:['smile','tongue','titter','laugh','sad','wronged','fastcry','cry','wail','mad','knock','curse','crazy','angry','ohmy','awkward','panic','shy','cute','envy','proud','struggle','quiet','shutup','doubt','despise','sleep','bye']}};
var arrTools={Cut:{t:'Cut'},Copy:{t:'Copy'},Paste:{t:'Paste'},Pastetext:{t:'Pastetext',h:isIE?0:1},Blocktag:{t:'Blocktag',h:1},Fontface:{t:'Fontface',h:1},FontSize:{t:'FontSize',h:1},Bold:{t:'Bold',s:'Ctrl+B'},Italic:{t:'Italic',s:'Ctrl+I'},Underline:{t:'Underline',s:'Ctrl+U'},Strikethrough:{t:'Strikethrough'},FontColor:{t:'FontColor',h:1},BackColor:{t:'BackColor',h:1},SelectAll:{t:'SelectAll'},Removeformat:{t:'Removeformat'},Align:{t:'Align',h:1},List:{t:'List',h:1},Outdent:{t:'Outdent'},Indent:{t:'Indent'},Link:{t:'Link',s:'Ctrl+L',h:1},Unlink:{t:'Unlink'},Anchor:{t:'Anchor',h:1},Img:{t:'Img',h:1},Flash:{t:'Flash',h:1},Media:{t:'Media',h:1},Hr:{t:'Hr'},Emot:{t:'Emot',s:'ctrl+e',h:1},Table:{t:'Table',h:1},Source:{t:'Source'},Preview:{t:'Preview'},Print:{t:'Print',s:'Ctrl+P'},Fullscreen:{t:'Fullscreen',s:'Esc'},About:{t:'About'}};
var toolsThemes={
mini:'Bold,Italic,Underline,Strikethrough,|,Align,List,|,Link,Img',
simple:'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,|,Align,List,Outdent,Indent,|,Link,Img,Emot',
full:'Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Anchor,Img,Flash,Media,Hr,Emot,Table,|,Source,Preview,Print,Fullscreen'};
toolsThemes.mfull=toolsThemes.full.replace(/\|(,Align)/i,'/$1');
var arrDbClick={'a':'Link','img':'Img','embed':'Embed'},uploadInputname='filedata';
var arrEntities={'<':'<','>':'>','"':'"','®':'®','©':'©'};//实体
var regEntities=/[<>"®©]/g;
var Xheditor = function(textarea, options)
{
var _this=this,_text=textarea,_jText=$(_text),_jForm=_jText.closest('form'),_jTools,_jArea,_win,_jWin,_doc,_jDoc;
var bookmark;
var bInit=false,bSource=false,bFullscreen=false,bCleanPaste=false,outerScroll,bShowBlocktag=false,sLayoutStyle='',ev=null,timer,bDisableHoverExec=false,bQuickHoverExec=false;
var lastPoint=null,lastAngle=null;//鼠标悬停显示
var editorHeight=0;
var settings=_this.settings=$.extend({},XHEDITOR.settings,options );
var plugins=settings.plugins,strPlugins=[];
if(plugins)
{
arrTools=$.extend({},arrTools,plugins);
$.each(plugins, function(n){
strPlugins.push(n);
});
strPlugins=strPlugins.join(',');
}
if(settings.tools.match(/^\s*(m?full|simple|mini)\s*$/i))
{
var toolsTheme=toolsThemes[$.trim(settings.tools)];
settings.tools=(settings.tools.match(/m?full/i)&&plugins)?toolsTheme.replace('Table','Table,'+strPlugins):toolsTheme;//插件接在full的Table后面
}
//如需删除关于按钮,请往官方网站购买商业授权:http://xheditor.com/service
//在未购买商业授权的情况下私自去除xhEditor的版权信息,您将得不到官方提供的任何技术支持和BUG反馈服务,并且我们将对您保留法律诉讼的权利
//请支持开源项目
if(!settings.tools.match(/(^|,)\s*About\s*(,|$)/i))settings.tools+=',About';
settings.tools=settings.tools.split(',');
if(settings.editorRoot)editorRoot=settings.editorRoot;
if(bAir===false)editorRoot=getLocalUrl(editorRoot,'abs');
if(settings.urlBase)settings.urlBase=getLocalUrl(settings.urlBase,'abs');
//基本控件名
var idCSS='xheCSS_'+settings.skin,idContainer='xhe'+xCount+'_container',idTools='xhe'+xCount+'_Tool',idIframeArea='xhe'+xCount+'_iframearea',idIframe='xhe'+xCount+'_iframe',idFixFFCursor='xhe'+xCount+'_fixffcursor';
var headHTML='',bodyClass='',skinPath=editorRoot+'xheditor_skin/'+settings.skin+'/',arrEmots=itemEmots,urlType=settings.urlType,urlBase=settings.urlBase,emotPath=settings.emotPath,emotPath=emotPath?emotPath:editorRoot+'xheditor_emot/',selEmotGroup='';
arrEmots=$.extend({},arrEmots,settings.emots);
emotPath=getLocalUrl(emotPath,'rel',urlBase?urlBase:null);//返回最短表情路径
bShowBlocktag=settings.showBlocktag;
if(bShowBlocktag)bodyClass+=' showBlocktag';
var arrShortCuts=[];
this.init=function()
{
//加载样式表
if($('#'+idCSS).length===0)$('head').append('<link id="'+idCSS+'" rel="stylesheet" type="text/css" href="'+skinPath+'ui.css" />');
//初始化编辑器
var textareaWidth=_jText.outerWidth(),textareaHeight=_jText.outerHeight();
var editorWidth = settings.width || _text.style.width || (textareaWidth>10?textareaWidth:0);
editorHeight = settings.height || _text.style.height || (textareaHeight>10?textareaHeight:150);//默认高度
if(/^\d+(?:\.\d+)?$/.test(editorWidth)){
editorWidth += 'px';
}
if(is(editorHeight,'string'))editorHeight=editorHeight.replace(/[^\d]+/g,'');
//编辑器CSS背景
var editorBackground=settings.background || _text.style.background;
//工具栏内容初始化
var arrToolsHtml=['<span class="xheGStart"/>'],tool,cn,regSeparator=/\||\//i;
$.each(settings.tools,function(i,n)
{
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGEnd"/>');
if(n==='|')arrToolsHtml.push('<span class="xheSeparator"/>');
else if(n==='/')arrToolsHtml.push('<br />');
else
{
tool=arrTools[n];
if(!tool)return;
if(tool.c)cn=tool.c;
else cn='xheIcon xheBtn'+n;
arrToolsHtml.push('<span><a href="#" title="{#'+tool.t+'}" cmd="'+n+'" class="xheButton xheEnabled" tabindex="-1" role="button"><span class="'+cn+'" unselectable="on" style="font-size:0;color:transparent;text-indent:-999px;">'+tool.t+'</span></a></span>');
if(tool.s)_this.addShortcuts(tool.s,n);
}
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGStart"/>');
});
arrToolsHtml.push('<span class="xheGEnd"/><br />');
_jText.after($('<input type="text" id="'+idFixFFCursor+'" style="position:absolute;display:none;" /><span id="'+idContainer+'" class="xhe_'+settings.skin+'" style="display:none"><table cellspacing="0" cellpadding="0" class="xheLayout" style="'+(editorWidth!='0px'?'width:'+editorWidth+';':'')+'height:'+editorHeight+'px;" role="presentation"><tr><td id="'+idTools+'" class="xheTool" unselectable="on" style="height:1px;" role="presentation"></td></tr><tr><td id="'+idIframeArea+'" class="xheIframeArea" role="presentation"><iframe frameborder="0" id="'+idIframe+'" src="javascript:;" style="width:100%;"></iframe></td></tr></table></span>'));
_jTools=$('#'+idTools);_jArea=$('#'+idIframeArea);
headHTML='<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link rel="stylesheet" href="'+skinPath+'iframe.css"/>';
var loadCSS=settings.loadCSS;
if(loadCSS)
{
if(is(loadCSS,'array'))for(var i in loadCSS)headHTML+='<link rel="stylesheet" href="'+loadCSS[i]+'"/>';
else
{
if(loadCSS.match(/\s*<style(\s+[^>]*?)?>[\s\S]+?<\/style>\s*/i))headHTML+=loadCSS;
else headHTML+='<link rel="stylesheet" href="'+loadCSS+'"/>';
}
}
var iframeHTML='<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>'+headHTML+'<title>{#defaultReadTip} '+(settings.readTip?settings.readTip:'')+'</title>';
if(editorBackground)iframeHTML+='<style>html{background:'+editorBackground+';}</style>';
iframeHTML+='</head><body spellcheck="0" class="editMode'+bodyClass+'"></body></html>';
_this.win=_win=$('#'+idIframe)[0].contentWindow;
_jWin=$(_win);
try{
this.doc=_doc = _win.document;_jDoc=$(_doc);
_doc.open();
_doc.write(getLang(iframeHTML));
_doc.close();
if(isIE)_doc.body.contentEditable='true';
else _doc.designMode = 'On';
}catch(e){}
setTimeout(setOpts,300);
_this.setSource();
_win.setInterval=null;//针对jquery 1.3无法操作iframe window问题的hack
//添加工具栏
_jTools.append(getLang(arrToolsHtml.join(''))).bind('mousedown contextmenu',returnFalse).click(function(event)
{
var jButton=$(event.target).closest('a');
if(jButton.is('.xheEnabled'))
{
clearTimeout(timer);//取消悬停执行
_jTools.find('a').attr('tabindex','-1');//无障碍支持
ev=event;
_this.exec(jButton.attr('cmd'));
}
return false;
});
_jTools.find('.xheButton').hover(function(event){//鼠标悬停执行
var jButton=$(this),delay=settings.hoverExecDelay;
var tAngle=lastAngle;lastAngle=null;
if(delay===-1||bDisableHoverExec||!jButton.is('.xheEnabled'))return false;
if(tAngle&&tAngle>10)//检测误操作
{
bDisableHoverExec=true;
setTimeout(function(){bDisableHoverExec=false;},100);
return false;
}
var cmd=jButton.attr('cmd'),bHover=arrTools[cmd].h===1;
if(!bHover)
{
_this.hidePanel();//移到非悬停按钮上隐藏面板
return false;
}
if(bQuickHoverExec)delay=0;
if(delay>=0)timer=setTimeout(function(){
ev=event;
lastPoint={x:ev.clientX,y:ev.clientY};
_this.exec(cmd);
},delay);
},function(event){lastPoint=null;if(timer)clearTimeout(timer);}).mousemove(function(event){
if(lastPoint)
{
var diff={x:event.clientX-lastPoint.x,y:event.clientY-lastPoint.y};
if(Math.abs(diff.x)>1||Math.abs(diff.y)>1)
{
if(diff.x>0&&diff.y>0)
{
var tAngle=Math.round(Math.atan(diff.y/diff.x)/0.017453293);
if(lastAngle)lastAngle=(lastAngle+tAngle)/2
else lastAngle=tAngle;
}
else lastAngle=null;
lastPoint={x:event.clientX,y:event.clientY};
}
}
});
//初始化面板
_jPanel=$('#xhePanel');
_jShadow=$('#xheShadow');
_jCntLine=$('#xheCntLine');
if(_jPanel.length===0)
{
_jPanel=$('<div id="xhePanel"></div>').mousedown(function(ev){ev.stopPropagation()});
_jShadow=$('<div id="xheShadow"></div>');
_jCntLine=$('<div id="xheCntLine"></div>');
setTimeout(function(){
$(document.body).append(_jPanel).append(_jShadow).append(_jCntLine);
},10);
}
//切换显示区域
$('#'+idContainer).show();
_jText.hide();
_jArea.css('height',editorHeight-_jTools.outerHeight());
if(isIE&browerVer<8)setTimeout(function(){_jArea.css('height',editorHeight-_jTools.outerHeight());},1);
//绑定内核事件
_jText.focus(_this.focus);
_jForm.submit(saveResult).bind('reset', loadReset);//绑定表单的提交和重置事件
if(settings.submitID)$('#'+settings.submitID).mousedown(saveResult);//自定义绑定submit按钮
$(window).bind('unload beforeunload',saveResult).bind('resize',fixFullHeight);
$(document).mousedown(clickCancelPanel);
if(!bCheckEscInit){$(document).keydown(checkEsc);bCheckEscInit=true;}
_jWin.focus(function(){if(settings.focus)settings.focus();}).blur(function(){if(settings.blur)settings.blur();});
if(isWebkit){
_jWin.click(fixAppleSel);
}
_jDoc.mousedown(clickCancelPanel).keydown(checkShortcuts).keypress(forcePtag).dblclick(checkDblClick).bind('mousedown click',function(ev){_jText.trigger(ev.type);});
if(isIE)
{
//IE控件上Backspace会导致页面后退
_jDoc.keydown(function(ev){var rng=_this.getRng();if(ev.which===8&&rng.item){$(rng.item(0)).remove();return false;}});
//修正IE拖动img大小不更新width和height属性值的问题
function fixResize(ev)
{
var jImg=$(ev.target),v;
if(v=jImg.css('width'))jImg.css('width','').attr('width',v.replace(/[^0-9%]+/g, ''));
if(v=jImg.css('height'))jImg.css('height','').attr('height',v.replace(/[^0-9%]+/g, ''));
}
_jDoc.bind('controlselect',function(ev){
ev=ev.target;if(!$.nodeName(ev,'IMG'))return;
$(ev).unbind('resizeend',fixResize).bind('resizeend',fixResize);
});
}
//无障碍支持
_jDoc.keydown(function(e){
var which=e.which;
if(e.altKey&&which>=49&&which<=57){
_jTools.find('a').attr('tabindex','0');
_jTools.find('.xheGStart').eq(which-49).next().find('a').focus();
_doc.title='\uFEFF\uFEFF';
return false;
}
}).click(function(){
_jTools.find('a').attr('tabindex','-1');
});
_jTools.keydown(function(e){
var which=e.which;
if(which==27){
_jTools.find('a').attr('tabindex','-1');
_this.focus();
}
else if(e.altKey&&which>=49&&which<=57){
_jTools.find('.xheGStart').eq(which-49).next().find('a').focus();
return false;
}
});
var jBody=$(_doc.documentElement);
//自动清理粘贴内容
if(isOpera)jBody.bind('keydown',function(e){if(e.ctrlKey&&e.which===86)cleanPaste();});
else jBody.bind(isIE?'beforepaste':'paste',cleanPaste);
//禁用编辑区域的浏览器默认右键菜单
if(settings.disableContextmenu)jBody.bind('contextmenu',returnFalse);
//HTML5编辑区域直接拖放上传
if(settings.html5Upload)jBody.bind('dragenter dragover',function(ev){var types;if((types=ev.originalEvent.dataTransfer.types)&&$.inArray('Files', types)!==-1)return false;}).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0){
var i,cmd,arrCmd=['Link','Img','Flash','Media'],arrExt=[],strExt;
for(i in arrCmd){
cmd=arrCmd[i];
if(settings['up'+cmd+'Url']&&settings['up'+cmd+'Url'].match(/^[^!].*/i))arrExt.push(cmd+':,'+settings['up'+cmd+'Ext']);//允许上传
}
if(arrExt.length===0)return false;//禁止上传
else strExt=arrExt.join(',');
function getCmd(fileList){
var match,fileExt,cmd;
for(i=0;i<fileList.length;i++){
fileExt=fileList[i].name.replace(/.+\./,'');
if(match=strExt.match(new RegExp('(\\w+):[^:]*,'+fileExt+'(?:,|$)','i'))){
if(!cmd)cmd=match[1];
else if(cmd!==match[1])return 2;
}
else return 1;
}
return cmd;
}
cmd=getCmd(fileList);
if(cmd===1)alert(getLang('upload.extLimit',strExt.replace(/\w+:,/g,'')));
else if(cmd===2)alert(getLang('upload.typeLimit'));
else if(cmd){
_this.startUpload(fileList,settings['up'+cmd+'Url'],'*',function(arrMsg){
var arrUrl=[],msg,onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(var i=0,c=arrMsg.length;i<c;i++){
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)==='!')url=url.substr(1);
arrUrl.push(url);
}
_this.exec(cmd);
$('#xhe'+cmd+'Url').val(arrUrl.join(' '));
$('#xheSave').click();
});
}
return false;
}
});
//添加用户快捷键
var shortcuts=settings.shortcuts;
if(shortcuts)$.each(shortcuts,function(key,func){_this.addShortcuts(key,func);});
xCount++;
bInit=true;
if(settings.fullscreen)_this.toggleFullscreen();
else if(settings.sourceMode)setTimeout(_this.toggleSource,20);
//初始化所有插件
var plugins = settings.plugins;
if(plugins){
$.each(plugins, function(n,v){
var init = v.i;
if(init !== undefined){
init(_this);
}
});
}
return true;
}
this.remove=function()
{
_this.hidePanel();
saveResult();//卸载前同步最新内容到textarea
//取消绑定事件
_jText.unbind('focus',_this.focus);
_jForm.unbind('submit',saveResult).unbind('reset', loadReset);
if(settings.submitID)$('#'+settings.submitID).unbind('mousedown',saveResult);
$(window).unbind('unload beforeunload',saveResult).unbind('resize',fixFullHeight);
$(document).unbind('mousedown',clickCancelPanel);
$('#'+idContainer).remove();
$('#'+idFixFFCursor).remove();
_jText.show();
bInit=false;
}
this.saveBookmark=function(){
if(!bSource){
_this.focus();
var rng=_this.getRng();
rng=rng.cloneRange?rng.cloneRange():rng;
bookmark={'top':_jWin.scrollTop(),'rng':rng};
}
}
this.loadBookmark=function()
{
if(bSource||!bookmark)return;
_this.focus();
var rng=bookmark.rng;
if(isIE)rng.select();
else
{
var sel=_this.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
_jWin.scrollTop(bookmark.top);
bookmark=null;
}
this.focus=function()
{
if(!bSource)_win.focus();
else $('#sourceCode',_doc).focus();
if(isIE){
var rng=_this.getRng();
if(rng.parentElement&&rng.parentElement().ownerDocument!==_doc)_this.setTextCursor();//修正IE初始焦点问题
}
return false;
}
this.setTextCursor=function(bLast)
{
var rng=_this.getRng(true),cursorNode=_doc.body;
if(isIE || isIE11)rng.moveToElementText(cursorNode);
else{
var chileName=bLast?'lastChild':'firstChild';
while(cursorNode.nodeType!=3&&cursorNode[chileName]){cursorNode=cursorNode[chileName];}
rng.selectNode(cursorNode);
}
rng.collapse(bLast?false:true);
if(isIE || isIE11)rng.select();
else{var sel=_this.getSel();sel.removeAllRanges();sel.addRange(rng);}
}
this.getSel=function()
{
return _doc.selection ? _doc.selection : _win.getSelection();
}
this.getRng=function(bNew)
{
var sel,rng;
try{
if(!bNew){
sel=_this.getSel();
rng = sel.createRange ? sel.createRange() : sel.rangeCount > 0?sel.getRangeAt(0):null;
}
if(!rng)rng = _doc.body.createTextRange?_doc.body.createTextRange():_doc.createRange();
}catch (ex){}
return rng;
}
this.getParent=function(tag)
{
var rng=_this.getRng(),p;
if(!isIE)
{
p = rng.commonAncestorContainer;
if(!rng.collapsed)if(rng.startContainer === rng.endContainer&&rng.startOffset - rng.endOffset < 2&&rng.startContainer.hasChildNodes())p = rng.startContainer.childNodes[rng.startOffset];
}
else p=rng.item?rng.item(0):rng.parentElement();
tag=tag?tag:'*';p=$(p);
if(!p.is(tag))p=$(p).closest(tag);
return p;
}
this.getSelect=function(format)
{
var sel=_this.getSel(),rng=_this.getRng(),isCollapsed=true;
if (!rng || rng.item)isCollapsed=false
else isCollapsed=!sel || rng.boundingWidth === 0 || rng.collapsed;
if(format==='text')return isCollapsed ? '' : (rng.text || (sel.toString ? sel.toString() : ''));
var sHtml;
if(rng.cloneContents)
{
var tmp=$('<div></div>'),c;
c = rng.cloneContents();
if(c)tmp.append(c);
sHtml=tmp.html();
}
else if(is(rng.item))sHtml=rng.item(0).outerHTML;
else if(is(rng.htmlText))sHtml=rng.htmlText;
else sHtml=rng.toString();
if(isCollapsed)sHtml='';
sHtml=_this.processHTML(sHtml,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
return sHtml;
}
this.pasteHTML=function(sHtml,bStart)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
var sel=_this.getSel(),rng=_this.getRng();
if(bStart!==undefined)//非覆盖式插入
{
if(rng.item)
{
var item=rng.item(0);
rng=_this.getRng(true);
rng.moveToElementText(item);
rng.select();
}
rng.collapse(bStart);
}
sHtml+='<'+(isIE?'img':'span')+' id="_xhe_temp" width="0" height="0" />';
if(rng.insertNode)
{
if($(rng.startContainer).closest('style,script').length>0)return false;//防止粘贴在style和script内部
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(sHtml));
}
else
{
if(sel.type.toLowerCase()==='control'){sel.clear();rng=_this.getRng();};
rng.pasteHTML(sHtml);
}
var jTemp=$('#_xhe_temp',_doc),temp=jTemp[0];
if(isIE)
{
rng.moveToElementText(temp);
rng.select();
}
else
{
rng.selectNode(temp);
sel.removeAllRanges();
sel.addRange(rng);
}
jTemp.remove();
}
this.pasteText=function(text,bStart)
{
if(!text)text='';
text=_this.domEncode(text);
text = text.replace(/\r?\n/g, '<br />');
_this.pasteHTML(text,bStart);
}
this.appendHTML=function(sHtml)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
$(_doc.body).append(sHtml);
_this.setTextCursor(true);
}
this.domEncode=function(text)
{
return text.replace(regEntities,function(c){return arrEntities[c];});
}
this.setSource=function(sHtml)
{
bookmark=null;
if(typeof sHtml!=='string'&&sHtml!=='')sHtml=_text.value;
if(bSource)$('#sourceCode',_doc).val(sHtml);
else
{
if(settings.beforeSetSource)sHtml=settings.beforeSetSource(sHtml);
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
sHtml=_this.processHTML(sHtml,'write');
if(isIE){//修正IE会删除可视内容前的script,style,<!--
_doc.body.innerHTML='<img id="_xhe_temp" width="0" height="0" />'+sHtml;//修正IE会删除&符号后面代码的问题
$('#_xhe_temp',_doc).remove();
}
else _doc.body.innerHTML=sHtml;
}
}
this.processHTML=function(sHtml,mode)
{
var appleClass=' class="Apple-style-span"',
arrFontsize = settings.listFontsize;
if(mode==='write')
{//write
sHtml=sHtml.replace(/(<(\/?)(\w+))((?:\s+[\w\-:]+\s*=\s*(?:"[^"]*"|'[^']*'|[^>\s]+))*)\s*((\/?)>)/g,function(all,left,end1,tag,attr,right,end2){
tag=tag.toLowerCase();
if(isMozilla){
if(tag==='strong')tag='b';
else if(tag==='em')tag='i';
}
else if(isWebkit){
if(tag==='strong'){tag='span';if(!end1)attr+=appleClass+' style="font-weight: bold;"';}
else if(tag==='em'){tag='span';if(!end1)attr+=appleClass+' style="font-style: italic;"';}
else if(tag==='u'){tag='span';if(!end1)attr+=appleClass+' style="text-decoration: underline;"';}
else if(tag==='strike'){tag='span';if(!end1)attr+=appleClass+' style="text-decoration: line-through;"';}
}
var emot,addClass='';
if(tag==='del')tag='strike';//编辑状态统一转为strike
else if(tag==='img'){
//恢复emot
attr=attr.replace(/\s+emot\s*=\s*("[^"]*"|'[^']*'|[^>\s]+)/i,function(all,v){
emot=v.match(/^(["']?)(.*)\1/)[2];
emot=emot.split(',');
if(!emot[1]){emot[1]=emot[0];emot[0]=''}
if(emot[0]==='default')emot[0]='';
return settings.emotMark?all:'';
});
}
else if(tag==='a'){
if(!attr.match(/ href=[^ ]/i)&&attr.match(/ name=[^ ]/i))addClass+=' xhe-anchor';
if(end2)right='></a>';
}
else if(tag==='table'&&!end1){
var tb=attr.match(/\s+border\s*=\s*("[^"]*"|'[^']*'|[^>\s]+)/i);
if(!tb||tb[1].match(/^(["']?)\s*0\s*\1$/))addClass+=' xhe-border';
}
var bAppleClass;
//处理属性
attr=attr.replace(/\s+([\w\-:]+)\s*=\s*("[^"]*"|'[^']*'|[^>\s]+)/g,function(all,n,v){
n=n.toLowerCase();
v=v.match(/^(["']?)(.*)\1/)[2];
aft='';//尾部增加属性
if(isIE&&n.match(/^(disabled|checked|readonly|selected)$/)&&v.match(/^(false|0)$/i))return '';
//恢复emot
if(tag==='img'&&emot&&n==='src')return '';
//保存属性值:src,href
if(n.match(/^(src|href)$/)){
aft=' _xhe_'+n+'="'+v+'"';
if(urlBase)v=getLocalUrl(v,'abs',urlBase);
}
//添加class
if(addClass&&n==='class'){
v+=' '+addClass;
addClass='';
}
//处理Safari style值
if(isWebkit&&n==='style'){
if(tag==='span'&&v.match(/(^|;)\s*(font-family|font-size|color|background-color)\s*:\s*[^;]+\s*(;|$)/i))bAppleClass=true;
}
return ' '+n+'="'+v+'"'+aft;
});
//恢复emot
if(emot){
var url=emotPath+(emot[0]?emot[0]:'default')+'/'+emot[1]+'.gif';
attr+=' src="'+url+'" _xhe_src="'+url+'"';
}
if(bAppleClass)attr+=appleClass;
if(addClass)attr+=' class="'+addClass+'"';
return '<'+end1+tag+attr+right;
});
if(isIE)sHtml = sHtml.replace(/'/ig, ''');
if(!isWebkit)
{
//style转font
function style2font(all,tag,left,style,right,content)
{
var attrs='',f,s1,s2,c;
f=style.match(/font-family\s*:\s*([^;"]+)/i);
if(f)attrs+=' face="'+f[1]+'"';
s1=style.match(/font-size\s*:\s*([^;"]+)/i);
if(s1)
{
s1=s1[1].toLowerCase();
for(var j=0;j<arrFontsize.length;j++)if(s1===arrFontsize[j].n||s1===arrFontsize[j].s){s2=j+1;break;}
if(s2)
{
attrs+=' size="'+s2+'"';
style=style.replace(/(^|;)(\s*font-size\s*:\s*[^;"]+;?)+/ig,'$1');
}
}
c=style.match(/(?:^|[\s;])color\s*:\s*([^;"]+)/i);
if(c)
{
var rgb;
if(rgb=c[1].match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){
c[1]='#';
for(var i=1;i<=3;i++){
c[1]+=('0'+(rgb[i]-0).toString(16)).slice(-2);
}
}
c[1]=c[1].replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
attrs+=' color="'+c[1]+'"';
}
style=style.replace(/(^|;)(\s*(font-family|color)\s*:\s*[^;"]+;?)+/ig,'$1');
if(attrs!=='')
{
if(style)attrs+=' style="'+style+'"';
return '<font'+(left?left:'')+attrs+(right?right:'')+'>'+content+"</font>";
}
else return all;
}
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)?\s*(?:font-family|font-size|color)\s*:[^"]*)"( [^>]*)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,style2font);//第3层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)?\s*(?:font-family|font-size|color)\s*:[^"]*)"( [^>]*)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,style2font);//第2层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)?\s*(?:font-family|font-size|color)\s*:[^"]*)"( [^>]*)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,style2font);//最里层
}
//表格单元格处理
sHtml = sHtml.replace(/<(td|th)(\s+[^>]*?)?>(\s| )*<\/\1>/ig,'<$1$2>'+(isIE?'':'<br />')+'</$1>');
}
else
{//read
if(isWebkit)
{
//转换apple的style为strong,em等
var arrAppleSpan=[{r:/font-weight\s*:\s*bold;?/ig,t:'strong'},{r:/font-style\s*:\s*italic;?/ig,t:'em'},{r:/text-decoration\s*:\s*underline;?/ig,t:'u'},{r:/text-decoration\s*:\s*line-through;?/ig,t:'strike'}];
function replaceAppleSpan(all,tag,attr1,attr2,content)
{
var attr=(attr1?attr1:'')+(attr2?attr2:'');
var arrPre=[],arrAft=[];
var regApple,tagApple;
for(var i=0;i<arrAppleSpan.length;i++)
{
regApple=arrAppleSpan[i].r;
tagApple=arrAppleSpan[i].t;
attr=attr.replace(regApple,function(){
arrPre.push("<"+tagApple+">");
arrAft.push("</"+tagApple+">");
return '';
});
}
attr=attr.replace(/\s+style\s*=\s*"\s*"/i,'');
return (attr?'<span'+attr+'>':'')+arrPre.join('')+content+arrAft.join('')+(attr?'</span>':'');
}
for(var i=0;i<2;i++){
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第3层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第2层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,replaceAppleSpan);//最里层
}
}
sHtml=sHtml.replace(/(<(\w+))((?:\s+[\w\-:]+\s*=\s*(?:"[^"]*"|'[^']*'|[^>\s]+))*)\s*(\/?>)/g,function(all,left,tag,attr,right){
tag=tag.toLowerCase();
//恢复属性值src,href
var saveValue;
attr=attr.replace(/\s+_xhe_(?:src|href)\s*=\s*("[^"]*"|'[^']*'|[^>\s]+)/i,function(all,v){saveValue=v.match(/^(["']?)(.*)\1/)[2];return '';});
if(saveValue&&urlType)saveValue=getLocalUrl(saveValue,urlType,urlBase);
attr=attr.replace(/\s+([\w\-:]+)\s*=\s*("[^"]*"|'[^']*'|[^>\s]+)/g,function(all,n,v){
n=n.toLowerCase();
v=v.match(/^(["']?)(.*)\1/)[2].replace(/"/g,"'");
if(n==='class'){//清理class属性
if(v.match(/^["']?(apple|webkit)/i))return '';
v=v.replace(/\s?xhe-[a-z]+/ig,'');
if(v==='')return '';
}
else if(n.match(/^((_xhe_|_moz_|_webkit_)|jquery\d+)/i))return '';//清理临时属性
else if(saveValue&&n.match(/^(src|href)$/i))return ' '+n+'="'+saveValue+'"';//恢复属性值src,href
else if(n==='style'){//转换font-size的keyword到px单位
v=v.replace(/(^|;)\s*(font-size)\s*:\s*([a-z-]+)\s*(;|$)/i,function(all,left,n,v,right){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(v===t.n){s=t.s;break;}
}
return left+n+':'+s+right;
});
}
return ' '+n+'="'+v+'"';
});
//img强制加alt
if(tag==='img'&&!attr.match(/\s+alt\s*=\s*("[^"]*"|'[^']*'|[^>\s]+)/i))attr+=' alt=""';
return left+attr+right;
});
//表格单元格处理
sHtml = sHtml.replace(/(<(td|th)(?:\s+[^>]*?)?>)\s*([\s\S]*?)(<br(\s*\/)?>)?\s*<\/\2>/ig,function(all,left,tag,content){return left+(content?content:' ')+'</'+tag+'>';});
//修正浏览器在空内容情况下多出来的代码
sHtml=sHtml.replace(/^\s*(?:<(p|div)(?:\s+[^>]*?)?>)?\s*(<span(?:\s+[^>]*?)?>\s*<\/span>|<br(?:\s+[^>]*?)?>| )*\s*(?:<\/\1>)?\s*$/i, '');
}
//写和读innerHTML前pre中<br>转\r\n
sHtml=sHtml.replace(/(<pre(?:\s+[^>]*?)?>)([\s\S]+?)(<\/pre>)/gi,function(all,left,code,right){
return left+code.replace(/<br\s*\/?>/ig,'\r\n')+right;
});
return sHtml;
}
this.getSource=function(bFormat)
{
var sHtml,beforeGetSource=settings.beforeGetSource;
if(bSource)
{
sHtml=$('#sourceCode',_doc).val();
if(!beforeGetSource)sHtml=_this.formatXHTML(sHtml,false);
}
else
{
sHtml=_this.processHTML(_doc.body.innerHTML,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml,bFormat);
if(beforeGetSource)sHtml=beforeGetSource(sHtml);
}
_text.value=sHtml;
return sHtml;
}
this.cleanWord=function(sHtml)
{
var cleanPaste=settings.cleanPaste;
if(cleanPaste>0&&cleanPaste<3&&/mso(-|normal)|WordDocument|<table\s+[^>]*?x:str|\s+class\s*=\s*"?xl[67]\d"/i.test(sHtml))
{
//区块标签清理
sHtml = sHtml.replace(/<!--[\s\S]*?-->|<!(--)?\[[\s\S]+?\](--)?>|<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
sHtml = sHtml.replace(/\r?\n/ig, '');
//保留Word图片占位
if(isIE){
sHtml = sHtml.replace(/<v:shapetype(\s+[^>]*)?>[\s\S]*<\/v:shapetype>/ig,'');
sHtml = sHtml.replace(/<v:shape(\s+[^>]+)?>[\s\S]*?<v:imagedata(\s+[^>]+)?>\s*<\/v:imagedata>[\s\S]*?<\/v:shape>/ig,function(all,attr1,attr2){
var match;
match = attr2.match(/\s+src\s*=\s*("[^"]+"|'[^']+'|[^>\s]+)/i);
if(match){
match = match[1].match(/^(["']?)(.*)\1/)[2];
var sImg ='<img src="'+editorRoot+'xheditor_skin/blank.gif'+'" _xhe_temp="true" class="wordImage"';
match = attr1.match(/\s+style\s*=\s*("[^"]+"|'[^']+'|[^>\s]+)/i);
if(match){
match = match[1].match(/^(["']?)(.*)\1/)[2];
sImg += ' style="' + match + '"';
}
sImg += ' />';
return sImg;
}
return '';
});
}
else{
sHtml = sHtml.replace(/<img( [^<>]*(v:shapes|msohtmlclip)[^<>]*)\/?>/ig,function(all,attr){
var match,str = '<img src="'+editorRoot+'xheditor_skin/blank.gif'+'" _xhe_temp="true" class="wordImage"';
match = attr.match(/ width\s*=\s*"([^"]+)"/i);
if(match)str += ' width="'+match[1]+'"';
match = attr.match(/ height\s*=\s*"([^"]+)"/i);
if(match)str += ' height="'+match[1]+'"';
return str + ' />';
});
}
sHtml=sHtml.replace(/(<(\/?)([\w\-:]+))((?:\s+[\w\-:]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^>\s]+))?)*)\s*(\/?>)/g,function(all,left,end,tag,attr,right){
tag=tag.toLowerCase();
if((tag.match(/^(link)$/)&&attr.match(/file:\/\//i))||tag.match(/:/)||(tag==='span'&&cleanPaste===2))return '';
if(!end){
attr=attr.replace(/\s([\w\-:]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^>\s]+))?/ig,function(all,n,v){
n=n.toLowerCase();
if(/:/.test(n))return '';
v=v.match(/^(["']?)(.*)\1/)[2];
if(cleanPaste===1){//简单清理
switch(tag){
case 'p':
if(n === 'style'){
v=v.replace(/"|"/ig,"'").replace(/\s*([^:]+)\s*:\s*(.*?)(;|$)/ig,function(all,n,v){
return /^(text-align)$/i.test(n)?(n+':'+v+';'):'';
}).replace(/^\s+|\s+$/g,'');
return v?(' '+n+'="'+v+'"'):'';
}
break;
case 'span':
if(n === 'style'){
v=v.replace(/"|"/ig,"'").replace(/\s*([^:]+)\s*:\s*(.*?)(;|$)/ig,function(all,n,v){
return /^(color|background|font-size|font-family)$/i.test(n)?(n+':'+v+';'):'';
}).replace(/^\s+|\s+$/g,'');
return v?(' '+n+'="'+v+'"'):'';
}
break;
case 'table':
if(n.match(/^(cellspacing|cellpadding|border|width)$/i))return all;
break;
case 'td':
if(n.match(/^(rowspan|colspan)$/i))return all;
if(n === 'style'){
v=v.replace(/"|"/ig,"'").replace(/\s*([^:]+)\s*:\s*(.*?)(;|$)/ig,function(all,n,v){
return /^(width|height)$/i.test(n)?(n+':'+v+';'):'';
}).replace(/^\s+|\s+$/g,'');
return v?(' '+n+'="'+v+'"'):'';
}
break;
case 'a':
if(n.match(/^(href)$/i))return all;
break;
case 'font':
case 'img':
return all;
break;
}
}
else if(cleanPaste===2){
switch(tag){
case 'td':
if(n.match(/^(rowspan|colspan)$/i))return all;
break;
case 'img':
return all;
}
}
return '';
});
}
return left+attr+right;
});
//空内容的标签
for(var i=0;i<3;i++)sHtml = sHtml.replace( /<([^\s>]+)(\s+[^>]*)?>\s*<\/\1>/g,'');
//无属性的无意义标签
function cleanEmptyTag(all,tag,content){
return content;
}
for(var i=0;i<3;i++)sHtml = sHtml.replace(/<(span|a)>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,cleanEmptyTag);//第3层
for(var i=0;i<3;i++)sHtml = sHtml.replace(/<(span|a)>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,cleanEmptyTag);//第2层
for(var i=0;i<3;i++)sHtml = sHtml.replace(/<(span|a)>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,cleanEmptyTag);//最里层
//合并多个font
for(var i=0;i<3;i++)sHtml = sHtml.replace(/<font(\s+[^>]+)><font(\s+[^>]+)>/ig,function(all,attr1,attr2){
return '<font'+attr1+attr2+'>';
});
//清除表格间隙里的空格等特殊字符
sHtml=sHtml.replace(/(<(\/?)(tr|td)(?:\s+[^>]+)?>)[^<>]+/ig,function(all,left,end,tag){
if(!end&&/^td$/i.test(tag))return all;
else return left;
});
}
return sHtml;
}
this.cleanHTML=function(sHtml)
{
sHtml = sHtml.replace(/<!?\/?(DOCTYPE|html|body|meta)(\s+[^>]*?)?>/ig, '');
var arrHeadSave;sHtml = sHtml.replace(/<head(?:\s+[^>]*?)?>([\s\S]*?)<\/head>/i, function(all,content){arrHeadSave=content.match(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig);return '';});
if(arrHeadSave)sHtml=arrHeadSave.join('')+sHtml;
sHtml = sHtml.replace(/<\??xml(:\w+)?(\s+[^>]*?)?>([\s\S]*?<\/xml>)?/ig, '');
if(!settings.internalScript)sHtml = sHtml.replace(/<script(\s+[^>]*?)?>[\s\S]*?<\/script>/ig, '');
if(!settings.internalStyle)sHtml = sHtml.replace(/<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
if(!settings.linkTag||!settings.inlineScript||!settings.inlineStyle)sHtml=sHtml.replace(/(<(\w+))((?:\s+[\w-]+\s*=\s*(?:"[^"]*"|'[^']*'|[^>\s]+))*)\s*(\/?>)/ig,function(all,left,tag,attr,right){
if(!settings.linkTag&&tag.toLowerCase()==='link')return '';
if(!settings.inlineScript)attr=attr.replace(/\s+on(?:click|dblclick|mouse(down|up|move|over|out|enter|leave|wheel)|key(down|press|up)|change|select|submit|reset|blur|focus|load|unload)\s*=\s*("[^"]*"|'[^']*'|[^>\s]+)/ig,'');
if(!settings.inlineStyle)attr=attr.replace(/\s+(style|class)\s*=\s*("[^"]*"|'[^']*'|[^>\s]+)/ig,'');
return left+attr+right;
});
sHtml=sHtml.replace(/<\/(strong|b|u|strike|em|i)>((?:\s|<br\/?>| )*?)<\1(\s+[^>]*?)?>/ig,'$2');//连续相同标签
return sHtml;
}
this.formatXHTML=function(sHtml,bFormat){
var emptyTags = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");//HTML 4.01
var blockTags = makeMap("address,applet,blockquote,button,center,dd,dir,div,dl,dt,fieldset,form,frameset,h1,h2,h3,h4,h5,h6,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,table,tbody,td,tfoot,th,thead,tr,ul,script");//HTML 4.01
var inlineTags = makeMap("a,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");//HTML 4.01
var closeSelfTags = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrsTags = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var cdataTags = makeMap("script,style");
var tagReplac={'b':'strong','i':'em','s':'del','strike':'del'};
var regTag=/<(?:\/([^\s>]+)|!([^>]*?)|([\w\-:]+)((?:"[^"]*"|'[^']*'|[^"'<>])*)\s*(\/?))>/g;
var regAttr = /\s*([\w\-:]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s]+)))?/g;
var results=[],stack=[];
stack.last = function(){return this[ this.length - 1 ];};
var match,tagIndex,nextIndex=0,tagName,tagCDATA,arrCDATA,text;
var lvl=-1,lastTag='body',lastTagStart,stopFormat=false;
while(match=regTag.exec(sHtml)){
tagIndex = match.index;
if(tagIndex>nextIndex){//保存前面的文本或者CDATA
text=sHtml.substring(nextIndex,tagIndex);
if(tagCDATA)arrCDATA.push(text);
else onText(text);
}
nextIndex = regTag.lastIndex;
if(tagName=match[1]){//结束标签
tagName=processTag(tagName);
if(tagCDATA&&tagName===tagCDATA){//结束标签前输出CDATA
onCDATA(arrCDATA.join(''));
tagCDATA=null;
arrCDATA=null;
}
if(!tagCDATA){