arisu.js 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/js/base.js ADDED
@@ -0,0 +1,1884 @@
1
+
2
+ /* ========================================================================
3
+ * 常用JS方法
4
+ * 2024年6月4日 21:41:04
5
+ * ========================================================================
6
+
7
+ // 导入
8
+ import b from './base'
9
+
10
+ // 1.1 基础方法
11
+ // 添加class
12
+ b("#id").addClass('test')
13
+ // 是否包含某个class
14
+ console.log(b("#id").hasClass('test'))//true
15
+ // 删除class
16
+ b("#id").removeClass('test');
17
+ // 切换class
18
+ b('.myclass').toggleClass('hi').toggleClass('hi')//加入再删除
19
+ // 选择不包含某个选择器的标签
20
+ console.log(b('div').not('.myclass')); //选择除了.myclass的div
21
+ // 判断当前选择器是否为某种标签,或者某状态如, :disabled
22
+ console.log(b('#movetest').is('button'))
23
+ console.log(b('#movetest').is(':disabled'))
24
+ // 返回祖节点,不传参数返回自己
25
+ console.log(b('.myspan').closest('div.myclass').html())
26
+ // 当前标签的下一个标签,如果是class多个标签则则包含第一个class开始到最后一个class的下一个标签
27
+ console.log(b('.myclass').next());
28
+ // 当前标签之后的所有标签,如果是class则从第一个class开始算
29
+ console.log($('.myclass').nextAll())
30
+ // 当前标签的上一个标签,如果是class多个标签则则包含倒数第二个class开始到第一个class的上一个标签
31
+ console.log(b('.myclass').prev());
32
+ // 当前标签之前的所有标签,如果是class则从最后一个class开始算
33
+ console.log($('.myclass').prevAll())
34
+ // 返回只包含第一个元素的base类
35
+ console.log($('.myclass').first());
36
+ // 查询当前对象下的元素
37
+ console.log(b('body').find('.myclass'))
38
+ // 查找父类标签
39
+ b.l(b("#id").parent());
40
+ // 查找祖先标签
41
+ b.l(b("#id").parents("div"));
42
+ // 返回兄弟节点
43
+ console.log(b("#id").siblings());
44
+ // 返回一级子元素,多个对象则为多个子元素
45
+ b.l(b(".ce-txt").children());
46
+ // 返回元素下标
47
+ console.log(b("#id").index());
48
+ // 事件绑定
49
+ b("#id").on("focus", () => {...
50
+ // 点击事件
51
+ b(".e2").click(function() { ...
52
+ // 焦点事件
53
+ b(".e2").focus(function() { ...
54
+ // 用于监听<input>、<select>和<textarea>元素值的变化
55
+ b('.myInput').change((e) => { console.log(e.currentTarget.value); })
56
+ // 主动触发事件
57
+ trigger('click', { message: 'Hello, World!' });
58
+ // 删除标签
59
+ b("#id").remove();
60
+ // data属性绑定设置
61
+ <div id="id" data-name="arisu">data测试</div>
62
+ b("#id").data('age', '99');
63
+ console.log(b("#id").data('age')); //99
64
+ console.log(b("#id").data('name')); //arisu
65
+ // attr、removeAttr页面标签属性增删
66
+ b("#id").attr('sex', 'man').removeAttr('data-name');
67
+ // 当前元素坐标,eg:{ 3633, 180 }
68
+ b("#id").offset();
69
+ // 获取滚动条位置距离页面顶部的长度
70
+ console.log(b(window).scrollTop());
71
+ // 获取当前页面真实高度
72
+ b(window).height()
73
+ // 获取或者设置输入框下拉框等标签中的值
74
+ b('.myInput').val('test').attr('data-c', 'd')
75
+ // 样式修改
76
+ b("#id").css('font-size','2rem').text('hhh')
77
+ // 获取变更dom文本信息
78
+ console.log(b("#id").text());
79
+ console.log(b("#id").text('载入中...'));
80
+ // 设置或获取html代码
81
+ console.log(b('.myclass').html('<h3>这是一个h3标签</h3>').html());
82
+ // 在当前选择器后插入代码
83
+ b('.myclass').after('<p>after加入P</p>');
84
+ // 在当前选择器内尾部加入代码
85
+ b('.myclass').append('<p>append加入P</p>').append('<span>append加入span</span>');
86
+ // 在当前选择器内起始位置加入代码
87
+ b("#id").prepend('<p>插入到内部头部</p>')
88
+ // 隐藏元素
89
+ b('.myclass').hide().css('font-size', '3rem');
90
+ // 显示元素
91
+ b('.myclass').show()
92
+ // 标签消失高度变0的关闭动画
93
+ b('.myElement').slideUp(500, function() { console.log('动画完成'); });
94
+ // 标签显示高度变复原的打开动画
95
+ b('.myElement').slideDown(500, function() { console.log('动画完成'); });
96
+ // 标签打开关闭切换
97
+ b('.myElement').slideToggle(500, function() { console.log('动画完成'); });
98
+
99
+ // 1.2 页面基础方法扩展
100
+ // 全选全清,<input type="checkbox" class="myCheckbox"><input type="checkbox" class="test">
101
+ b(".myCheckbox").checkAll('.test');
102
+ // 反选
103
+ b('#be-reverse-check').checkReverse('.be-check')
104
+ // 数字特效递增动画
105
+ b("#f").numStep({...
106
+ // 背景滚动动画
107
+ b(".ce-bg-ef").scrollBG({speed: 6});
108
+ // 点击切换激活项
109
+ b(".my-btn").setActive();
110
+ // 全屏loading
111
+ b('body').loading();
112
+ b("body").loading("complete");
113
+
114
+
115
+ // 2. 静态方法
116
+ // 2.1 基础静态方法
117
+ // 参数继承覆盖
118
+ b.extend( newOptions, defaults )
119
+ // 四舍五入,保留n位
120
+ b.toRound(3.14159, 2); //3.14
121
+ // 判断变量是否为空
122
+ if(b.isNull(变量)) {
123
+ // 如果为空设置默认值
124
+ b.setDefault(data.id, 0);
125
+ // 获取两个数组中的相同值
126
+ b.same([1,2], [7,9,4,2,5,6,1]) //[1, 2]
127
+ // 获取两个数组中的不相同值
128
+ b.different([1,2], [7,9,4,2,5,6,1]) //[7, 9, 4, 5, 6]
129
+ // 判断字符串是否为html标签,如<li></li><div></div><img/>返回true
130
+ console.log(b.isHtmlTag('<img />')); // true
131
+ // 判断变量是否为对象
132
+ console.log(b.isObject(custom));
133
+ // 允许插件扩展plugin静态方法
134
+ // 普通方法
135
+ function test(p1, p2) { console.log(this, p1, p2) } //Base... 3 4
136
+ Base.plugin('test', test);
137
+ b(".myclass").test(3,4)
138
+ // 插件,支持扩展插件,声明的插件或者方法调用不方便:new Base("#id").myPlugin(),直接使用b['test'] = test;绑定
139
+ +function(b) {
140
+ function myPlugin(options) {
141
+ this.each((element) => { b.l(element); });
142
+ return this;
143
+ }
144
+ b.fn.myPlugin = myPlugin;
145
+ }(Base);
146
+ // ajax异步请求
147
+ b.ajax({ url: "/data.json", success: (data) => { b.l(data) } })
148
+
149
+ // 2.2 页面常用方法
150
+ // 获取URL中的参数,rg: ..url?name=arisu
151
+ b.getParam("name"); //arisu
152
+ // 页面内缓慢移动,样式:html { scroll-behavior: smooth; }
153
+ b("#movetest").click((e) => { b.move("#id"); });
154
+ //字符串复杂度验证,表单验证
155
+ b.strValidation('abc123#', 3, 12);//8
156
+ // b.keys 常用键盘按钮
157
+ b.keys.enter //回车
158
+ // 常用快捷键事件绑定
159
+ b.hotkey(b.keys.enter, () => { b.l('你点击了enter') })
160
+ b.hotkey('Delete', () => { b.l('你点击了Delete') }) //b.keys没有预制的可以直接填键盘KEY
161
+ // 设置cookie
162
+ b.setCookie('username', 'JohnDoe');
163
+ // 获取cookie
164
+ console.log(b.getCookie('username')); // 输出: JohnDoe
165
+ // 删除cookie
166
+ b.removeCookie('username'); //b.getCookie('username')为null
167
+ // 数据库菜单数据生成ul列表树
168
+ const html = b.menu(data.trees, true); b('#nav-accordion').html(html) //<ul class="ce-accordion" id="nav-accordion"></ul>
169
+ // 数据库普通的数据列表转换成有层次的数组
170
+ b.l(b.menu2Tree(data.trees, 1, 1));
171
+ // 包含搜索按钮删除按钮的搜索框
172
+ b.search(function(txt) { if (txt) console.log(txt); });// 输入框文本
173
+
174
+
175
+ // 3. 其他常用方法、原生JS方法重写等
176
+ // 时间格式化
177
+ new Date().format("yyyy-MM-dd hh:mm:ss")//'2024-06-10 10:47:06'
178
+ // 数组根据下标删除扩展,返回执行完数组长度
179
+ ['a', 'b', 'c', 'd'].remove(-1);//删除最后一个元素返回3,数组为['a', 'b', 'c']
180
+ // 数组删除重复元素
181
+ [1, 2, 3, 1].unique() //[1, 2, 3]
182
+
183
+
184
+
185
+ * ======================================================================== */
186
+
187
+ class Base {
188
+
189
+ //支持new Base("div:eq(2)", ".container")、new Base(" > div", ".container")等格式选择器
190
+ constructor(selector, context) {
191
+ context = (context instanceof Base) ? context.elements[0] : (context || document);
192
+
193
+ if (typeof selector === 'string') {
194
+ if (context && typeof context === 'string') {
195
+ context = document.querySelector(context);
196
+ }
197
+ if (Base.isEqSelector(selector)) {
198
+ const ss = selector.split(':'),
199
+ htmlTag = ss[0],
200
+ eqIndexMatch = selector.match(/:eq\((\d+)\)/),
201
+ htmlIndex = parseInt(eqIndexMatch[1]);
202
+ const list = Base.contextQuerySelector(">" + htmlTag, context);
203
+ if (list.length > 0) {
204
+ this.elements = [ list[htmlIndex] ]
205
+ } else {
206
+ this.elements = [];
207
+ }
208
+ } else {
209
+ this.elements = Base.contextQuerySelector(selector, context);
210
+ }
211
+ } else if (selector instanceof NodeList || selector instanceof HTMLElement) {
212
+ this.elements = [ selector ];
213
+ } else if (selector instanceof Window) {
214
+ this.elements = [ window ];
215
+ } else if (selector !== null && typeof selector === 'object' && 'documentElement' in selector) {
216
+ this.elements = [ context ];
217
+ } else if (selector instanceof Array) {
218
+ this.elements = selector;
219
+ } else {
220
+ this.elements = [];
221
+ }
222
+ this.length = this.elements.length;
223
+ }
224
+
225
+ // length = 0
226
+
227
+ // 选择器遍历
228
+ each(callback) {
229
+ this.elements.forEach((element) => {
230
+ let index;
231
+ if (Array.isArray(this.elements)) {
232
+ index = this.elements.indexOf(element);
233
+ } else if (this.elements instanceof NodeList) {
234
+ index = Array.from(this.elements).indexOf(element);
235
+ } else {
236
+ index = -1;
237
+ }
238
+ callback(element, index);
239
+ });
240
+ return this;
241
+ }
242
+
243
+ /* ========================================================================
244
+ * 1 基础常用方法
245
+ * ======================================================================== */
246
+
247
+ // 1.1 基础方法
248
+
249
+ // 是否包含某个class
250
+ hasClass( className ) {
251
+ let result = false;
252
+ this.each((element) => {
253
+ result = element.classList.contains(className);
254
+ });
255
+ return result;
256
+ }
257
+
258
+ // 添加class
259
+ addClass(className) {
260
+ return this.each((element) => {
261
+ if (/\s/.test(className)) {
262
+ const classes = className.split(' ');
263
+ for (let i = 0; i < classes.length; i++) {
264
+ if (classes[i])
265
+ element.classList.add(classes[i]);
266
+ }
267
+ } else {
268
+ if (className)
269
+ element.classList.add(className);
270
+ }
271
+ });
272
+ }
273
+
274
+ // 删除class
275
+ removeClass(className) {
276
+ return this.each((element) => {
277
+ if (className === undefined) {
278
+ element.className = '';
279
+ } else if (className || className.length !== 0) {
280
+ if (/\s/.test(className)) {
281
+ const classes = className.split(' ');
282
+ for (let i = 0; i < classes.length; i++) {
283
+ if (classes[i])
284
+ element.classList.remove(classes[i].trim());
285
+ }
286
+ } else {
287
+ element.classList.remove(className.trim());
288
+ }
289
+ }
290
+ });
291
+ }
292
+
293
+ // 切换class
294
+ toggleClass(className) {
295
+ return this.each((element) => {
296
+ if (element.classList) {
297
+ element.classList.toggle(className);
298
+ } else {
299
+ let classes = element.className.split(/\s+/);
300
+ let existingIndex = classes.indexOf(className);
301
+ if (existingIndex >= 0) {
302
+ classes.splice(existingIndex, 1);
303
+ } else {
304
+ classes.push(className);
305
+ }
306
+ element.className = classes.join(' ');
307
+ }
308
+ })
309
+ }
310
+
311
+ // 选择不包含某个选择器的标签
312
+ not(selector) {
313
+ let excludedElements = (selector instanceof Base) ? selector.elements : Array.from(document.querySelectorAll(selector));
314
+ // if (selector instanceof Base) {
315
+ // let excludedElements = selector.elements;
316
+ // this.elements = Array.from(this.elements).filter((element) => {
317
+ // return !excludedElements.includes( element );
318
+ // });
319
+ // } else {
320
+ // let excludedElements = Array.from(document.querySelectorAll(selector));
321
+ this.elements = Array.from(this.elements).filter((element) => {
322
+ return !excludedElements.includes( element );
323
+ });
324
+ // }
325
+ return this;
326
+ }
327
+
328
+ // 判断当前选择器是否为某种标签,或者某状态如, :disabled
329
+ is(selector) {
330
+ let element = this.elements[0];
331
+ if (selector === ':visible') {
332
+ if (element.style.display === 'none' || element.style.visibility === 'hidden' ||
333
+ getComputedStyle(element).opacity === '0') {
334
+ return false;
335
+ }
336
+ } else if (selector === ':first-child') {
337
+ return element.parentNode.firstChild === element;
338
+ } else if (selector === ':last-child') {
339
+ // const parent = element.parentNode;
340
+ // for (let i = 0; i < parent.childNodes.length; i++) {
341
+ // const sibling = parent.childNodes[i];
342
+ // if (sibling.nodeType === Node.ELEMENT_NODE && sibling !== element) {
343
+ // return false; // 存在更后的兄弟元素,不是最后一个子元素
344
+ // }
345
+ // }
346
+ // return true;
347
+ const parent = element.parentNode,
348
+ children = parent.children;
349
+ return children[children.length - 1] === element;
350
+ } else {
351
+ return element.matches(selector);
352
+ }
353
+ }
354
+
355
+ // 返回父亲节点
356
+ closest(selector) {
357
+ let element = this.elements[0];
358
+
359
+ // 匹配传入的selector
360
+ const matchesSelector = element.matches || element.webkitMatchesSelector;//|| element.msMatchesSelector
361
+
362
+ // 如果元素本身匹配selector,则返回元素本身
363
+ if (matchesSelector.call(element, selector)) {
364
+ return this;
365
+ }
366
+ // 如果没有匹配,则向上遍历DOM树
367
+ let parent;
368
+ while ((parent = element.parentElement)) {
369
+ if (matchesSelector.call(parent, selector)) {
370
+ return new Base(parent);
371
+ }
372
+ element = parent;
373
+ }
374
+ return this;
375
+ }
376
+
377
+ // 当前标签的下一个标签,如果是class多个标签则则包含第一个class开始到最后一个class的下一个标签
378
+ next() {
379
+ if (this.elements.length === 1) {
380
+ return new Base(this.elements[0].nextElementSibling);
381
+ } else if (this.elements.length > 1) {
382
+ let b = new Base(this.elements[0].nextElementSibling);
383
+ this.each((element, i) => {
384
+ if (i > 1) {
385
+ b.elements.push(element)
386
+ if (i === this.elements.length - 1) {
387
+ b.elements.push( element.nextElementSibling )
388
+ }
389
+ }
390
+ })
391
+ return b;
392
+ } else {
393
+ return null;
394
+ }
395
+ }
396
+
397
+ // 当前标签之后的所有标签,如果是class则从第一个class开始算 console.log($('.myclass').nextAll())
398
+ nextAll(selector) {
399
+ // 创建一个数组来存储所有之后的兄弟节点
400
+ const nextElements = [];
401
+ let element = this.elements[0],
402
+ nextSibling = element.nextSibling,
403
+ parentElement = element.parentElement;
404
+ while (nextSibling) {
405
+ if (nextSibling.nodeType === 1) {
406
+ // 如果没有提供选择器,或者nextSibling匹配给定的选择器
407
+ if (!selector || nextSibling.matches(selector)) {
408
+ nextElements.unshift(nextSibling); // 使用unshift将元素添加到数组开头,以保持顺序
409
+ }
410
+ }
411
+ nextSibling = nextSibling.nextSibling;
412
+ if (nextSibling === null && nextElements.length === 0 && parentElement.firstChild === element) {
413
+ break;
414
+ }
415
+ }
416
+ this.elements = nextElements;
417
+ this.length = this.elements.length;
418
+ return this;
419
+ }
420
+
421
+ // 当前标签的上一个标签,如果是class多个标签则则包含第一个class开始到最后一个class的下一个标签
422
+ prev() {
423
+ if (this.elements.length === 1) {
424
+ return new Base(this.elements[0].previousElementSibling);
425
+ } else if (this.elements.length > 1) {
426
+ let b = new Base(this.elements[0].previousElementSibling);
427
+ this.each((element, i) => {
428
+ if (i > 1) {
429
+ b.elements.push(element)
430
+ if (i === this.elements.length - 1) {
431
+ b.elements.push( element.previousElementSibling )
432
+ }
433
+ }
434
+ })
435
+ return b;
436
+ } else {
437
+ return null;
438
+ }
439
+ }
440
+
441
+ // 当前标签之前的所有标签,如果是class则从最后一个class开始算
442
+ prevAll(selector) {
443
+ // 创建一个数组来存储所有之前的兄弟节点
444
+ const prevElements = [];
445
+ let element = this.elements[this.elements.length - 1],
446
+ prevSibling = element.previousSibling,
447
+ parentElement = element.parentElement;
448
+ while (prevSibling) {
449
+ if (prevSibling.nodeType === 1) {
450
+ // 如果没有提供选择器,或者prevSibling匹配给定的选择器
451
+ if (!selector || prevSibling.matches(selector)) {
452
+ prevElements.unshift(prevSibling); // 使用unshift将元素添加到数组开头,以保持顺序
453
+ }
454
+ }
455
+ prevSibling = prevSibling.previousSibling;
456
+ if (prevSibling === null && prevElements.length === 0 && parentElement.firstChild === element) {
457
+ break;
458
+ }
459
+ }
460
+ this.elements = prevElements;
461
+ this.length = this.elements.length;
462
+ return this;
463
+ }
464
+
465
+ // 返回只包含第一个元素的base类
466
+ first() {
467
+ return new Base([ this.elements[0] ]);
468
+ }
469
+
470
+ // 查询当前对象下的元素
471
+ find(context) {
472
+ if (context && context.trim() === "option:selected") {
473
+ this.each((element) => {
474
+ if (element.type === 'select-one' || element.type === 'select-multiple') {
475
+ return new Base(element.options[element.selectedIndex]);
476
+ }
477
+ });
478
+ // selectElement.options[selectElement.selectedIndex];
479
+ } else {
480
+ return new Base(context, this.elements[0]);
481
+ }
482
+ // let element = this.elements[0],
483
+ // ctx = element.querySelectorAll( context );
484
+ // if (ctx.length > 0) {
485
+ // this.elements = ctx;
486
+ // } else {
487
+ // this.elements = [ ];
488
+ // }
489
+ // return this;
490
+ //
491
+ }
492
+
493
+ // 查找父类标签
494
+ parent() {
495
+ let element = this.elements[0];
496
+ return element ? new Base(element.parentNode) : new Base();
497
+ }
498
+
499
+ // 查找祖先标签
500
+ parents(selector) {
501
+ const parents = [];
502
+ let element = this.elements[0],
503
+ parent = element.parentNode;
504
+ while (parent && parent !== document) {
505
+ if (!selector || parent.matches(selector)) {
506
+ parents.push(parent);
507
+ }
508
+ parent = parent.parentNode;
509
+ }
510
+ return new Base(parents);
511
+ }
512
+
513
+ // 返回兄弟节点console.log(b("#id").siblings());
514
+ siblings() {
515
+ let element = this.elements[0];
516
+ if (!element || !(element.nodeType === 1)) {
517
+ return new Base();
518
+ } else {
519
+ // 获取元素的父元素
520
+ let parent = element.parentNode;
521
+ if (parent) {
522
+ let siblingsArray = [];
523
+ // 遍历父元素的子节点
524
+ for (let i = 0; i < parent.childNodes.length; i++) {
525
+ let child = parent.childNodes[i];
526
+ if (child.nodeType === 1 && child !== element) {
527
+ siblingsArray.push(child);
528
+ }
529
+ }
530
+ return new Base(siblingsArray);
531
+ } else {
532
+ // 没有父元素
533
+ return new Base();
534
+ }
535
+ }
536
+ }
537
+
538
+ // 返回一级子元素
539
+ children() {
540
+ let children = [];
541
+ this.each((element) => {
542
+ for (const child in element.children) {
543
+ if (element.children.hasOwnProperty(child)) {
544
+ children.push(element.children[child]);
545
+ }
546
+ }
547
+ })
548
+ return new Base(children);
549
+ }
550
+
551
+ // 返回元素下标
552
+ index() {
553
+ const element = this.elements[0],
554
+ siblings = element.parentNode.children;
555
+ for (let i = 0; i < siblings.length; i++) {
556
+ if (siblings[i] === element) {
557
+ return i;
558
+ }
559
+ }
560
+ return -1;
561
+ }
562
+
563
+ size() {
564
+ return this.elements ? this.elements.length : 0;
565
+ }
566
+
567
+ // 事件绑定,相当于bind
568
+ on(eventType, handler) {
569
+ return this.each(function(element) {
570
+ element.addEventListener(eventType, handler);
571
+ });
572
+ }
573
+
574
+ // 事件解除绑定,只能删除指定方法
575
+ off(eventName, callback) {
576
+ return this.each(function(element) {
577
+ if (element.removeEventListener) {
578
+ if (callback) {
579
+ element.removeEventListener(eventName, callback);
580
+ } else {
581
+ }
582
+ }
583
+ });
584
+ }
585
+
586
+ // 点击事件
587
+ click(handler) {
588
+ if (typeof handler === 'function') {
589
+ this.on('click', handler);
590
+ } else {
591
+ // 如果没有参数传入,则触发元素的点击事件
592
+ this.each((el) => {
593
+ const event = new MouseEvent('click', {
594
+ bubbles: true,
595
+ cancelable: true,
596
+ view: window
597
+ });
598
+ el.dispatchEvent(event);
599
+ });
600
+ }
601
+ return this;
602
+ }
603
+
604
+ // 焦点事件
605
+ focus(handler) {
606
+ if (typeof handler === 'function') {
607
+ this.on('focus', handler);
608
+ }
609
+ return this;
610
+ }
611
+
612
+ // 用于监听<input>、<select>和<textarea>元素值的变化b('.myInput').change((e) => { console.log(e.currentTarget.value); })
613
+ change(handler) {
614
+ if (typeof handler === 'function') {
615
+ let element = this.elements[0];
616
+ if (element.addEventListener) {
617
+ // 对于现代浏览器
618
+ return this.each(function(element) {
619
+ element.addEventListener('change', handler, false);
620
+ });
621
+ } else if (element.attachEvent) {
622
+ // 对于老版本的IE浏览器
623
+ return this.each(function(element) {
624
+ element.attachEvent('onchange', callback);
625
+ });
626
+ } else {
627
+ return this.each(function(element) {
628
+ element.onchange = handler;
629
+ });
630
+ }
631
+ }
632
+ }
633
+
634
+ // 主动触发事件,trigger('click', { message: 'Hello, World!' });
635
+ trigger(eventName, eventData) {
636
+ this.each(function(element) {
637
+ let event;
638
+ try {
639
+ // 对于现代浏览器
640
+ event = new CustomEvent(eventName, {
641
+ detail: eventData,
642
+ bubbles: true,
643
+ cancelable: true
644
+ });
645
+ } catch (e) {
646
+ // 对于旧版浏览器
647
+ event = document.createEvent('CustomEvent');
648
+ event.initCustomEvent(eventName, true, true, eventData);
649
+ }
650
+ element.dispatchEvent(event);
651
+ });
652
+ }
653
+
654
+ // 删除标签
655
+ remove() {
656
+ return this.each((element) => {
657
+ element.parentNode.removeChild(element);
658
+ });
659
+ }
660
+
661
+ // data属性绑定设置
662
+ data( key, value ) {
663
+ if ( key === undefined ) {
664
+ throw new Error('读取的或设置的键值不能为空');
665
+ }
666
+
667
+ let cache,
668
+ elem = this.elements[0],
669
+ // 获取与元素关联的缓存对象
670
+ id = Base.expando,
671
+ isCache = id && Base.cache[ id ];
672
+
673
+ if ( value !== undefined ) {
674
+ // 如果尚未创建缓存对象,则创建它
675
+ if ( !isCache ) {
676
+ cache = {};
677
+ // 生成唯一的缓存键
678
+ elem[ Base.expando ] = cache[ Base.expando ] = id;
679
+ // 将缓存对象存储在全局 Base.cache 中
680
+ Base.cache[ id ] = isCache = cache;
681
+ }
682
+ // 存储数据到缓存对象中
683
+ isCache[ Base.camelCase( key ) ] = value;
684
+ return this;
685
+ } else {
686
+ if (!isCache) return undefined; else
687
+ return isCache[ Base.camelCase( key ) ] ? isCache[ Base.camelCase( key ) ] : Base.dataAttr( elem, Base.camelCase( key ) )
688
+ }
689
+ }
690
+
691
+ // 清除data属性绑定的值
692
+ removeData( key ) {
693
+ delete Base.cache[ Base.expando ][ key ];
694
+ }
695
+
696
+ // attr 方法实现
697
+ attr(attributeName, value) {
698
+ let element = this.elements[0];
699
+ if (value === undefined) {
700
+ return element.getAttribute(attributeName);
701
+ } else {
702
+ return this.each((element) => {
703
+ element.setAttribute(attributeName, value);
704
+ });
705
+ }
706
+ }
707
+
708
+ // removeAttr 方法实现
709
+ removeAttr(attributeName) {
710
+ return this.each((element) => {
711
+ if (typeof element.removeAttribute === 'function') {
712
+ element.removeAttribute(attributeName);
713
+ }
714
+ });
715
+ }
716
+
717
+ // 当前元素坐标,eg:{ 3633, 180 }
718
+ offset() {
719
+ let rect = this.elements[0].getBoundingClientRect(),
720
+ scrollTop = window.pageYOffset || document.documentElement.scrollTop,
721
+ scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
722
+ return {
723
+ top: rect.top + scrollTop,
724
+ left: rect.left + scrollLeft
725
+ };
726
+ }
727
+
728
+ // 获取滚动条位置距离页面顶部的长度
729
+ scrollTop() {
730
+ let element = this.elements[0];
731
+ if (element instanceof Window) {
732
+ return (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
733
+ } else {
734
+ return document.documentElement.scrollTop;
735
+ }
736
+ }
737
+
738
+ // 获取当前选择器第一个元素真实高度
739
+ height() {
740
+ let element = this.elements[0];
741
+ if (element === window) {
742
+ return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
743
+ }
744
+ return element.offsetHeight ;
745
+ }
746
+
747
+ // 获取当前选择器第一个元素真实宽度
748
+ width() {
749
+ let element = this.elements[0];
750
+ // 如果传入的是window对象,直接返回视口宽度
751
+ if (element === window) {
752
+ return window.innerWidth || document.documentElement.clientWidth;
753
+ }
754
+ return element.offsetWidth;
755
+ }
756
+
757
+ // 获取或者设置输入框下拉框等标签中的值
758
+ val(newValue) {
759
+ let element = this.elements[0];
760
+ if (element.type === 'select-multiple') {
761
+ // 对于多选select元素
762
+ if (newValue !== undefined) {// 设置值
763
+ for (let i = element.options.length - 1; i >= 0; i--) {
764
+ element.options[i].selected = element.options[i].value === newValue;
765
+ }
766
+ return this;
767
+ } else {// 获取值
768
+ let selectedValues = [];
769
+ for (let i = 0; i < element.options.length; i++) {
770
+ if (element.options[i].selected) {
771
+ selectedValues.push(element.options[i].value);
772
+ }
773
+ }
774
+ return selectedValues;
775
+ }
776
+ } else {
777
+ if (newValue !== undefined) {// 设置值
778
+ element.value = newValue;
779
+ return this;
780
+ } else {// 获取值
781
+ return element.value;
782
+ }
783
+ }
784
+ }
785
+
786
+ // 样式修改
787
+ css(propertyName, value) {
788
+ if (this.elements.length === 0) return false;
789
+
790
+ if (value === undefined) {
791
+ if (Base.isObject(propertyName)) {
792
+ // 当propertyName为对象时表示需要设置多个属性
793
+ return this.each(element => {
794
+ for (const key in propertyName) {
795
+ if (propertyName.hasOwnProperty(key)) {
796
+ element.style[key] = propertyName[key];
797
+ }
798
+ }
799
+ });
800
+ } else {
801
+ // 获取值
802
+ return this.elements[0].style[propertyName];
803
+ }
804
+ } else {// 设置值
805
+ return this.each(element => {
806
+ element.style[propertyName] = value;
807
+ });
808
+ }
809
+ }
810
+
811
+ // 文字写入
812
+ text(content) {
813
+ let element = this.elements[0];
814
+ if (content === undefined) {
815
+ let textContent = '';
816
+ let childNodes = element.childNodes;
817
+ for (let i = 0; i < childNodes.length; i++) {
818
+ let node = childNodes[i];
819
+ if (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE) {
820
+ textContent += node.textContent || node.innerText || '';
821
+ }
822
+ }
823
+ return textContent;
824
+ } else {
825
+ return this.each((element) => {
826
+ while (element.firstChild) {
827
+ element.removeChild(element.firstChild);
828
+ }
829
+ element.appendChild(document.createTextNode(content));
830
+ });
831
+ }
832
+ }
833
+
834
+ // 设置或者或者html代码
835
+ html(content) {
836
+ if (content !== undefined) {
837
+ return this.each((element) => {
838
+ if (element && element.nodeType === 1) {
839
+ element.innerHTML = content;
840
+ }
841
+ })
842
+ } else {
843
+ let element = this.elements[0];
844
+ if (element && element.nodeType === 1) {
845
+ return element.innerHTML;
846
+ }
847
+ }
848
+ }
849
+
850
+ // 在当前选择器后插入代码
851
+ after(html) {
852
+ return this.each((element) => {
853
+ // 插入html方法,参数为'beforeBegin', 'afterBegin', 'beforeEnd', 'afterEnd'
854
+ element.insertAdjacentHTML('afterend', html);
855
+ })
856
+ }
857
+
858
+ // 在当前选择器内尾部加入代码
859
+ append(content) {
860
+ return this.each((element) => {
861
+ // 创建一个临时的div元素用于包装HTML字符串
862
+ let tempDiv = document.createElement('div');
863
+ // content放入tempDiv
864
+ if (typeof content === 'string') {
865
+ tempDiv.innerHTML = content;
866
+ } else if (content instanceof Node) {
867
+ tempDiv.appendChild(content); // Node直接可以使用
868
+ } else if (content instanceof NodeList) {
869
+ for (let i = 0; i < content.length; i++) {
870
+ tempDiv.appendChild(content[i]);// NodeList 遍历使用
871
+ }
872
+ }
873
+ // 将tempDiv中的所有子节点移动到element中
874
+ while (tempDiv.firstChild) {
875
+ element.appendChild(tempDiv.firstChild);
876
+ }
877
+ return element;
878
+ })
879
+ }
880
+
881
+ // 在当前选择器内起始位置加入代码
882
+ prepend(content) {
883
+ return this.each((element) => {
884
+ // 创建一个临时的div元素用于包装HTML字符串
885
+ let tempDiv = document.createElement('div');
886
+ // content放入tempDiv
887
+ if (typeof content === 'string') {
888
+ tempDiv.innerHTML = content;
889
+ } else if (content instanceof Node) {
890
+ tempDiv.appendChild(content); // Node直接可以使用
891
+ } else if (content instanceof NodeList) {
892
+ for (let i = 0; i < content.length; i++) {
893
+ tempDiv.appendChild(content[i]);// NodeList 遍历使用
894
+ }
895
+ }
896
+ // 将tempDiv中的所有子节点移动到element中
897
+ while (tempDiv.firstChild) {
898
+ element.insertBefore(tempDiv.firstChild, element.firstChild);
899
+ }
900
+ return element;
901
+ })
902
+ }
903
+
904
+ // 隐藏元素
905
+ // hide() {
906
+ // return this.each((element) => {
907
+ // if (element && element.nodeType === 1) {
908
+ // element.style.display = 'none';
909
+ // }
910
+ // });
911
+ // }
912
+ hide(duration, callback) {
913
+ return this.each((element) => {
914
+ element.style.display = 'block';
915
+ if (duration) {
916
+ setTimeout(() => {
917
+ element.style.display = 'none';
918
+ if (callback && typeof callback === 'function') {
919
+ callback(element);
920
+ }
921
+ }, duration);
922
+ } else {
923
+ element.style.display = 'none';
924
+ if (callback && typeof callback === 'function') {
925
+ callback(element);
926
+ }
927
+ }
928
+ });
929
+ }
930
+
931
+ // 显示元素
932
+ show(duration, callback) {
933
+ return this.each((element) => {
934
+ element.style.display = 'block';
935
+ if (duration) {
936
+ setTimeout(() => {
937
+ element.style.display = 'block';
938
+ if (callback && typeof callback === 'function') {
939
+ callback(element);
940
+ }
941
+ }, duration);
942
+ } else {
943
+ element.style.display = 'block';
944
+ if (callback && typeof callback === 'function') {
945
+ callback(element);
946
+ }
947
+ }
948
+ });
949
+ }
950
+
951
+ // 标签消失高度变0的关闭动画,300MS刚刚好
952
+ slideUp(duration, callback) {
953
+ const options = b.extend({ duration: duration, callback: callback }, { duration: 300, callback: false })
954
+ return this.each((element) => {
955
+ const computedStyle = window.getComputedStyle(element),
956
+ height = element.offsetHeight;
957
+
958
+ let paddingTop = computedStyle.getPropertyValue('padding-top'),
959
+ paddingBottom = computedStyle.getPropertyValue('padding-bottom'),
960
+ marginTop = computedStyle.getPropertyValue('margin-top'),
961
+ marginBottom = computedStyle.getPropertyValue('margin-bottom');
962
+ if (paddingTop && paddingTop.includes('px'))
963
+ paddingTop = paddingTop.replace(/px/g, '');
964
+ if (paddingBottom && paddingBottom.includes('px'))
965
+ paddingBottom = paddingBottom.replace(/px/g, '');
966
+ if (marginTop && marginTop.includes('px'))
967
+ marginTop = marginTop.replace(/px/g, '');
968
+ if (marginBottom && marginBottom.includes('px'))
969
+ marginBottom = marginBottom.replace(/px/g, '');
970
+
971
+ // element.style.transition = 'height ' + options.duration + 'ms ease-in-out';
972
+ element.style.transition = 'none';
973
+ element.style.overflow = 'hidden'; // 隐藏超出元素的内容
974
+
975
+ function step(startTime) {
976
+ const now = performance.now(),
977
+ timeElapsed = now - startTime,
978
+ newHeight = Math.max(0, height - (timeElapsed / options.duration) * height),// 计算当前应该设置的高度
979
+ newPaddingTop = Math.max(0, paddingTop - (timeElapsed / options.duration) * paddingTop),
980
+ newPaddingBottom = Math.max(0, paddingBottom - (timeElapsed / options.duration) * paddingBottom),
981
+ newMarginTop = Math.max(0, marginTop - (timeElapsed / options.duration) * marginTop),
982
+ newMarginBottom = Math.max(0, marginBottom - (timeElapsed / options.duration) * marginBottom);
983
+ element.style.height = newHeight + `px`;
984
+ element.style.paddingTop = newPaddingTop + `px`;
985
+ element.style.paddingBottom = newPaddingBottom + `px`;
986
+ element.style.marginTop = newMarginTop + `px`;
987
+ element.style.marginBottom = newMarginBottom + `px`;
988
+ // 如果还没到达目标高度,则继续下一帧
989
+ if (timeElapsed < options.duration) {
990
+ requestAnimationFrame(step.bind(null, startTime));
991
+ } else {
992
+ // 过渡完成后清除过渡效果,以便后续操作
993
+ element.style.transition = '';
994
+ element.style.height = '';
995
+ element.style.display = 'none';
996
+ options.callback && options.callback();
997
+ }
998
+ }
999
+ requestAnimationFrame(step);
1000
+ });
1001
+ }
1002
+
1003
+ // 标签显示高度变复原的打开动画
1004
+ slideDown(duration, callback) {
1005
+ const options = b.extend({ duration: duration, callback: callback }, { duration: 300, callback: false })
1006
+ return this.each((element) => {
1007
+ // 获取元素当前的高度和初始的 display 状态
1008
+ let startHeight = element.offsetHeight,
1009
+ display = element.style.display,
1010
+ mainDuration = options.duration * 7 / 10,
1011
+ pmDuration = options.duration * 3 / 10;
1012
+ if (display === 'none') {
1013
+ element.style.display = '';
1014
+ startHeight = 0; // 如果元素是隐藏的,则从 0 开始
1015
+ }
1016
+
1017
+ let endHeight = element.scrollHeight, // 目标高度是元素的 scrollHeight
1018
+ changeHeight = endHeight - startHeight,
1019
+ startTime = null;
1020
+
1021
+ // 动画函数
1022
+ function step(timestamp) {
1023
+ if (!startTime) startTime = timestamp;
1024
+ let progress = timestamp - startTime;
1025
+ if (progress > mainDuration) progress = mainDuration;
1026
+ let newHeight = ease(progress, startHeight, changeHeight, mainDuration);
1027
+ element.style.height = newHeight + 'px';
1028
+
1029
+ if (progress < mainDuration) {
1030
+ window.requestAnimationFrame(step);
1031
+ } else {
1032
+ element.style.transition = 'padding ' + pmDuration + 'ms ease, margin ' + pmDuration + 'ms ease';
1033
+ // element.style.transition = 'all ' + pmDuration + 'ms ease';
1034
+ element.style.margin = '';
1035
+ element.style.padding = '';
1036
+ element.style.height = '';
1037
+ options.callback && options.callback();
1038
+ }
1039
+ }
1040
+ // 线性缓动函数
1041
+ function ease(t, b, c, d) {
1042
+ t /= d / 2;
1043
+ if (t < 1) return c / 2 * t * t + b;
1044
+ t--;
1045
+ return -c / 2 * (t * (t - 2) - 1) + b;
1046
+ }
1047
+ window.requestAnimationFrame(step);
1048
+ });
1049
+ }
1050
+
1051
+ // 标签打开关闭切换
1052
+ slideToggle(duration, callback) {
1053
+ const target = this,
1054
+ options = b.extend({ duration: duration, callback: callback }, { duration: 500, callback: false })
1055
+ let isOpen = true;
1056
+ this.each((element) => {
1057
+ if (element.style.display === 'none') {
1058
+ isOpen = false;
1059
+ }
1060
+ });
1061
+ if (isOpen) {
1062
+ target.slideUp(options.duration, options.callback);
1063
+ } else {
1064
+ target.slideDown(options.duration, options.callback);
1065
+ }
1066
+ }
1067
+
1068
+ // 1.2 页面常用方法扩展
1069
+
1070
+ // 全选全清
1071
+ checkAll(checkboxes) {
1072
+ const options = Base.extend({ checkboxes: checkboxes }, { checkboxes: '.be-check' });
1073
+ return this.each((element) => {
1074
+ let iCheckboxes = document.querySelectorAll(options.checkboxes);
1075
+
1076
+ element.addEventListener('change', function() {
1077
+ iCheckboxes.forEach(function(checkbox) {
1078
+ checkbox.checked = element.checked;
1079
+ })
1080
+ })
1081
+ })
1082
+ }
1083
+
1084
+ /**
1085
+ * 反选
1086
+ <pre>
1087
+ <a href="javascript:" id="be-reverse-check">反选</a>
1088
+ <label><input type="checkbox" className="be-check" checked="checked"/>选项一</label>
1089
+ <label><input type="checkbox" className="be-check"/>选项二</label>
1090
+
1091
+ b('#be-reverse-check').checkReverse('.be-check')
1092
+ </pre>
1093
+ **/
1094
+ checkReverse(checkboxes) {
1095
+ const options = Base.extend({ checkboxes: checkboxes }, { checkboxes: '.be-check' });
1096
+ return this.each((element) => {
1097
+ let iCheckboxes = document.querySelectorAll(options.checkboxes);
1098
+ element.addEventListener('click', function() {
1099
+ iCheckboxes.forEach(function(checkbox) {
1100
+ checkbox.checked = !checkbox.checked;
1101
+ })
1102
+ })
1103
+ })
1104
+ }
1105
+
1106
+ /**
1107
+ * 数字特效递增动画
1108
+ <pre>
1109
+ b("#btn").click(() => {
1110
+ b("#f").numStep({
1111
+ start: 0, //开始数字
1112
+ end: 100, //结束数字
1113
+ duration: 1500, //持续时间
1114
+ callback: function() {
1115
+ b.l('动画完成')
1116
+ }
1117
+ });
1118
+ })
1119
+ </pre>
1120
+ **/
1121
+ numStep(options) {
1122
+ const defaults = {
1123
+ start: 0, //开始数字
1124
+ end: 100, //结束数字
1125
+ duration: 1500, //持续时间
1126
+ callback: false //回调方法
1127
+ }
1128
+ options = b.extend(options, defaults);
1129
+ return this.each((element) => {
1130
+ let startTime = null;
1131
+ function numStepAnimation(currentTime) {
1132
+ if (startTime === null) startTime = currentTime;
1133
+ const progress = Math.min((currentTime - startTime) / options.duration, 1);
1134
+ const value = Math.floor(progress * (options.end - options.start) + options.start);
1135
+
1136
+ b(element).text(value);
1137
+
1138
+ if (progress < 1) {
1139
+ requestAnimationFrame(numStepAnimation);
1140
+ } else {
1141
+ if (typeof options.callback === 'function') {
1142
+ options.callback();
1143
+ }
1144
+ }
1145
+ }
1146
+ requestAnimationFrame(numStepAnimation);
1147
+ })
1148
+ }
1149
+
1150
+ /**
1151
+ * 背景滚动动画
1152
+ <pre>
1153
+ .ce-bg-ef {
1154
+ width: 100%;
1155
+ height: 400px;
1156
+ background: url("//arisu.cn/file/images/tools/bg/a10076f5-9649-43bb-877c-79615ced7536.png");
1157
+ transition: all 0.7s ease-in-out;
1158
+ }
1159
+
1160
+ <div class="ce-bg-ef"></div>
1161
+ b(".ce-bg-ef").scrollBG({speed: 6});
1162
+ </pre>
1163
+ **/
1164
+ scrollBG(options) {
1165
+ const defaults = { speed: 0 } //speed滚动速度,越小越快
1166
+ options = b.extend(options, defaults);
1167
+ return this.each((element) => {
1168
+ b( element ).css( "background-position", "50% 0px" );
1169
+ b( window ).on("scroll", () => {
1170
+ const myElement = b(element),
1171
+ y = myElement.offset().top,
1172
+ h = myElement.height(),
1173
+ windowY = myElement.scrollTop(),
1174
+ windowH = myElement.height();
1175
+ if (windowH + windowY > y && windowH + windowY < y + windowH + h) {
1176
+ const bgY = (y + h - windowY) / options.speed;
1177
+ myElement.css( "background-position", "50% -" + bgY + "px" );
1178
+ }
1179
+ });
1180
+ })
1181
+ }
1182
+
1183
+
1184
+ /**
1185
+ * 点击切换激活项(添加active class),已经激活则取消(删除active class)
1186
+ <pre>
1187
+ <button type="button" className="my-btn btn btn-success">我的按钮1</button>
1188
+ <button type="button" className="my-btn btn btn-success">我的按钮2</button>
1189
+
1190
+ b(".my-btn").setActive();
1191
+ </pre>
1192
+ **/
1193
+ setActive(options) {
1194
+ options = b.extend(options, { className: "active" });
1195
+ b(this.elements).click((e) => {
1196
+ const myTarget = b(e.currentTarget);
1197
+ if (myTarget.hasClass(options.className)) {
1198
+ myTarget.removeClass(options.className)
1199
+ } else {
1200
+ b(this.elements).removeClass(options.className);
1201
+ myTarget.addClass(options.className)
1202
+ }
1203
+ })
1204
+ }
1205
+
1206
+ /**
1207
+ * 全屏loading,
1208
+ <pre>
1209
+ import "istyle/src/css/loading/do-pr-loader.css";
1210
+ b('#c').click(() => {
1211
+ b('body').loading(); //开始loading
1212
+ setTimeout(function() {
1213
+ b("body").loading("complete"); //结束loading
1214
+ }, 3000);
1215
+ })
1216
+ </pre>
1217
+ **/
1218
+ loading(options) {
1219
+ let isComplete = false;
1220
+ if (typeof options !== 'undefined' && typeof options !== 'object') {
1221
+ isComplete = true;
1222
+ options = {};
1223
+ }
1224
+ options = b.extend(options, {
1225
+ isFull: true,
1226
+ loadingClass: '.do-preloader',
1227
+ template: '<div class="do-preloader"><span class="do-pr-loader"><span class="do-pr-lr"></span></span></div>'
1228
+ });
1229
+
1230
+ return this.each((element) => {
1231
+ if (isComplete) {
1232
+ b("> *", element).removeClass("be-blur-2");
1233
+ b(options.loadingClass).addClass("oy-0");
1234
+ setTimeout(() => {
1235
+ b("> *", element).removeClass("be-ts");
1236
+ b(options.loadingClass).remove();
1237
+ }, 300);
1238
+ } else {
1239
+ b(element).prepend(options.template);
1240
+ b("> *", element).addClass("be-ts").addClass("be-blur-2");
1241
+ if (options.template) {
1242
+ b(options.loadingClass).css('position', 'fixed').css('height', '100vh').css('width', '100vw')
1243
+ }
1244
+ }
1245
+ });
1246
+ }
1247
+
1248
+ /* ========================================================================
1249
+ * 2. 够外部直接调用的静态方法
1250
+ * ======================================================================== */
1251
+
1252
+ // 2.1 基础静态方法
1253
+ // 参数继承覆盖默认参数值
1254
+ // import b from './base'
1255
+ // let defaults = { name: 'arisu' }
1256
+ // let newOptions = { name: 'movss' }
1257
+ // console.log( b.extend( newOptions, defaults ) ); //{name: 'movss'}
1258
+ static extend = function( custom, defaults ) {
1259
+ if (custom) {
1260
+ let key, value;
1261
+ for (key in defaults) {
1262
+ if (defaults.hasOwnProperty(key)) {
1263
+ value = defaults[key];
1264
+ if (custom[key] == null) {
1265
+ custom[key] = value;
1266
+ }
1267
+ }
1268
+ }
1269
+ } else {
1270
+ return defaults;
1271
+ }
1272
+ return custom;
1273
+ }
1274
+
1275
+ // 字符串装换为驼峰格式
1276
+ static camelCase = function(str) {
1277
+ return str.replace(/-([a-z])/g, function(all, letter) {
1278
+ return letter.toUpperCase();
1279
+ });
1280
+ }
1281
+
1282
+ // 打印简写
1283
+ static l = function(...message) {
1284
+ if (window.console && window.console.log && message)
1285
+ console.log(...message);
1286
+ }
1287
+
1288
+ // 四舍五入,保留n位,eg: b.toRound(3.14159, 2); //3.14
1289
+ static toRound = function(number, save) {
1290
+ let result = parseFloat(number);
1291
+ if (result) result = Math.round(number * Math.pow(10, save)) / Math.pow(10, save); else result = 0;
1292
+ return result;
1293
+ }
1294
+
1295
+ // 判断变量是否为空,eg: if(b.isNull(变量)) {
1296
+ static isNull = function(target) {
1297
+ let result = true;
1298
+ if (target == null || target === "" || target === "undefined" || target === "null")
1299
+ result = false;
1300
+ return result;
1301
+ }
1302
+
1303
+ // 如果变量为空设置默认值,eg: setDefault(data.id, 0);
1304
+ static setDefault = function(target, defaultVal) {
1305
+ if (target == null || target === "" || target === "undefined" || target === "null")
1306
+ target = defaultVal;
1307
+ return target;
1308
+ }
1309
+
1310
+ // 获取两个数组中的相同值,eg: b.same([1,2], [7,9,4,2,5,6,1]) //[1, 2]
1311
+ static same = function(arr1, arr2) {
1312
+ return arr1.filter(function(v) {
1313
+ return arr2.indexOf(v) !== -1;
1314
+ });
1315
+ }
1316
+
1317
+ // 获取两个数组中的不相同值,eg: b.different([1,2], [7,9,4,2,5,6,1]) //[7, 9, 4, 5, 6]
1318
+ static different = function(arr1, arr2) {
1319
+ return arr1.concat(arr2).filter(function (v) {
1320
+ return arr1.indexOf(v) === -1 || arr2.indexOf(v) === -1;
1321
+ })
1322
+ }
1323
+
1324
+ // 判断字符串是否为html标签,如<li></li><div></div><img/>返回true
1325
+ static isHtmlTag(str) {
1326
+ const regex = /^<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>$|^<([a-z][a-z0-9]*)\b[^>]*\/>$/i;
1327
+ return regex.test(str);
1328
+ }
1329
+
1330
+ // 判断变量是否为对象
1331
+ static isObject(item) {
1332
+ return (item) ? (item && typeof item === 'object' && !Array.isArray( item ) && true) : false;
1333
+ }
1334
+
1335
+ // 允许插件扩展
1336
+ static plugin(pluginName, pluginFunction) {
1337
+ // Base.fn[pluginName] = pluginFunction;
1338
+ Base.fn[pluginName] = function() {
1339
+ pluginFunction()
1340
+ }
1341
+ }
1342
+
1343
+ // 创建一个新的临时html标签
1344
+ static createElement(htmlString) {
1345
+ // 创建一个新的临时div元素
1346
+ let tempDiv = document.createElement('div');
1347
+ // 将传入的HTML字符串设置为临时div的innerHTML
1348
+ tempDiv.innerHTML = htmlString.trim();
1349
+ // 获取临时div的第一个子元素,这就是我们创建的元素
1350
+ let newElement = tempDiv.firstChild;
1351
+ // 如果传入的HTML字符串包含多个元素,我们需要返回所有的子元素
1352
+ if (newElement.nodeType === Node.TEXT_NODE) {
1353
+ // 如果第一个节点是文本节点,那么真正的元素可能是它的下一个兄弟节点
1354
+ newElement = newElement.nextSibling;
1355
+ // 如果存在多个元素,我们需要收集它们并返回
1356
+ let fragment = document.createDocumentFragment();
1357
+ while (newElement) {
1358
+ fragment.appendChild(newElement);
1359
+ newElement = newElement.nextSibling;
1360
+ }
1361
+
1362
+ return fragment;
1363
+ }
1364
+ // 如果只创建了一个元素,直接返回它
1365
+ return newElement;
1366
+ }
1367
+
1368
+ // 异步请求
1369
+ static ajax(options) {
1370
+ const defaults = {
1371
+ url: '',
1372
+ method: 'GET',
1373
+ async: true,
1374
+ headerMap: { },// 'Content-Type': 'application/json'
1375
+ cache: 'default',
1376
+ dataType: 'json',
1377
+ data: null, // 可以是字符串、FormData 或 URLSearchParams
1378
+ // jsonp: options.jsonp,
1379
+ // jsonpCallback: options.jsonp,
1380
+ success: function() {},
1381
+ error: function() {},
1382
+ }
1383
+ options = b.extend(options, defaults);
1384
+ if (options.method === 'get') {
1385
+ if (!options.url.includes("?")) {
1386
+ let params = new URLSearchParams();
1387
+ for (let key in options.data) {
1388
+ if (options.data.hasOwnProperty(key)) {
1389
+ params.append(key, options.data[key]);
1390
+ }
1391
+ }
1392
+ options.url = options.url + '?' + params.toString();
1393
+ }
1394
+ options.data = null;
1395
+ }
1396
+
1397
+ if (fetch) {
1398
+ fetch(options.url, {
1399
+ method: options.method, // GET, POST, PUT, DELETE 等
1400
+ headers: new Headers(options.headerMap),
1401
+ cache: options.cache,
1402
+ body: options.data ? JSON.stringify(options.data) : null, // 如果需要发送 JSON 数据
1403
+ }).then(function(response) {
1404
+ if (!response.ok) {
1405
+ return Promise.reject(new Error('Failed to fetch resource'));
1406
+ }
1407
+ return (options.dataType === 'json') ? response.json() : response.text();
1408
+ }).then(function(data) {
1409
+ // 请求成功,调用 success 回调函数
1410
+ options.success(data);
1411
+ }).catch(function(error) {
1412
+ options.error(error);
1413
+ });
1414
+ } else {
1415
+ let xhr = new XMLHttpRequest();
1416
+ xhr.onload = function() {
1417
+ if (xhr.status >= 200 && xhr.status < 300) {
1418
+ let response;
1419
+ switch (options.dataType) {
1420
+ case 'json':
1421
+ try {
1422
+ response = JSON.parse(xhr.responseText);
1423
+ } catch (e) {
1424
+ options.error(e);
1425
+ return;
1426
+ }
1427
+ break;
1428
+ case 'text':
1429
+ response = xhr.responseText;
1430
+ break;
1431
+ default:
1432
+ response = xhr.responseText || xhr.response; // 假设是其他格式的数据
1433
+ }
1434
+ options.success(response, xhr.status, xhr);
1435
+ } else {
1436
+ let error = new Error('Request failed. Status: ' + xhr.status);
1437
+ // error.xhr = xhr;
1438
+ options.error(error);
1439
+ }
1440
+ };
1441
+ xhr.onerror = function() {
1442
+ options.error(new Error('Network Error'));
1443
+ };
1444
+ xhr.open(options.method, options.url, options.async); // 第三个参数表示异步
1445
+ // 设置请求头
1446
+ // xhr.setRequestHeader('Content-Type', 'application/json'); // 示例
1447
+ for (let key in options.headerMap) {
1448
+ if (options.headerMap.hasOwnProperty(key)) {
1449
+ xhr.setRequestHeader(key, options.headerMap[key]);
1450
+ }
1451
+ }
1452
+
1453
+ // 如果需要发送请求体(如 POST 请求),则发送数据
1454
+ if (options.data) {
1455
+ // xhr.send(JSON.stringify(options.data));
1456
+ // 或者如果是 FormData 或 URLSearchParams,直接发送
1457
+ xhr.send(options.data);
1458
+ } else {
1459
+ xhr.send(); // 对于 GET 请求或没有数据的 POST 请求
1460
+ }
1461
+ }
1462
+ }
1463
+
1464
+ // 2.2 页面常用方法
1465
+
1466
+ // 获取URL中的参数,eg: ..url?name=arisu,调用b.getParam("name"); //arisu
1467
+ static getParam = function(key) {
1468
+ let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
1469
+ let r = window.location.search.substr(1).match(reg);
1470
+ if (r != null) return unescape(r[2]); else return null;
1471
+ }
1472
+
1473
+ // 页面内缓慢移动,需要CSS3支持特效,html { scroll-behavior: smooth; }
1474
+ static move = function(target) {
1475
+ const t = document.querySelector(target);
1476
+ if (t) {
1477
+ let offset = new Base(t).offset();
1478
+ scrollTo( offset.left, offset.top );
1479
+ }
1480
+ }
1481
+
1482
+ /**
1483
+ * 字符串复杂度验证,表单验证
1484
+ * <pre>
1485
+ let lenMin = 3;
1486
+ let lenMax = 12;
1487
+ let result = b.strValidation('abc123#', lenMin, lenMax);//8
1488
+ if (result == 1) {
1489
+ console.log("字符串必须小于等于" + lenMin + ",或者大于等于" + lenMax);
1490
+ } else if (result == 2) {
1491
+ console.log("不能全部为数字");
1492
+ } else if (result == 3) {
1493
+ console.log("不能全部为字母");
1494
+ } else if (result == 4) {
1495
+ console.log("不能只有数字字母,必须包含特殊字符");
1496
+ } else if (result == 5) {
1497
+ console.log("不能只使用特殊字符");
1498
+ } else if (result == 8) {
1499
+ console.log("通过,包含字母数字及特殊字符");
1500
+ } else {
1501
+ console.log("没有可以匹配的,必须包含英文字母数字及键盘上的特殊字符");
1502
+ }
1503
+ * </pre>
1504
+ **/
1505
+ static strValidation = function(str, lenMin, lenMax) {
1506
+ let result = 0;
1507
+ let d1 = /^[^\u4e00-\u9fa5a-zA-Z\d,.,。]{0,32}$/;//全部为特殊字符
1508
+ let d4 = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]*$/;//包含字母数字及特殊字符
1509
+ let medium = /^[0-9a-zA-z]{0,32}$/;//包含字母数字
1510
+ let e1 = /^[0-9]{0,32}$/;//全部为数字
1511
+ let e2 = /^[a-zA-z]{0,32}$/;//全部为字母
1512
+
1513
+ if (str.length <= lenMin || str.length >= lenMax) {
1514
+ //字符串小于等于lenMin或者大于等于lenMax
1515
+ result = 1;
1516
+ } else if (e1.test(str)) {
1517
+ result = 2;
1518
+ } else if (e2.test(str)) {
1519
+ result = 3;
1520
+ } else if (medium.test(str)) {
1521
+ result = 4;
1522
+ } else if (d1.test(str)) {
1523
+ result = 5;
1524
+ // } else if (d2.test(str)) {
1525
+ // result = 6;
1526
+ // } else if (d3.test(str)) {
1527
+ // result = 7;
1528
+ } else if (d4.test(str)) {
1529
+ result = 8;
1530
+ }
1531
+ return result;
1532
+ }
1533
+
1534
+ // 常用快捷键事件绑定
1535
+ static keys = {
1536
+ 'esc': 'Escape',
1537
+ 'backspace': 'Backspace',
1538
+ 'space': ' ',
1539
+ 'enter': 'Enter',
1540
+ 'up': 'ArrowUp',
1541
+ 'down': 'ArrowDown',
1542
+ 'left': 'ArrowLeft',
1543
+ 'right': 'ArrowRight'
1544
+ };
1545
+ static hotkey(key, callback) {
1546
+ document.addEventListener('keydown', function(event) {
1547
+ if (key === event.key) {
1548
+ callback();
1549
+ }
1550
+ });
1551
+ }
1552
+
1553
+ // 设置cookie
1554
+ static setCookie(name, value, options = {}) {
1555
+ let expires = '',
1556
+ path = options.path || '/',
1557
+ domain = options.domain,
1558
+ secure = options.secure ? '; Secure' : '';
1559
+
1560
+ if (options.expires) {
1561
+ let date;
1562
+ if (typeof options.expires === 'number') {
1563
+ date = new Date();
1564
+ date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
1565
+ } else {
1566
+ date = options.expires;
1567
+ }
1568
+ expires = `; expires=${date.toUTCString()}`;
1569
+ }
1570
+ document.cookie = `${name}=${encodeURIComponent(value)}${expires}; path=${path}; domain=${domain || ''}${secure}`;
1571
+ }
1572
+
1573
+ // 获取cookie
1574
+ static getCookie(name) {
1575
+ let nameEQ = `${name}=`,
1576
+ ca = document.cookie.split(';');
1577
+ for (let i = 0; i < ca.length; i++) {
1578
+ let c = ca[i];
1579
+ while (c.charAt(0) === ' ') c = c.substring(1, c.length);
1580
+ if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
1581
+ }
1582
+ return null;
1583
+ }
1584
+
1585
+ // 删除cookie
1586
+ static removeCookie(name, options = {}) {
1587
+ this.setCookie(name, '', { ...options, expires: -1 });
1588
+ }
1589
+
1590
+ // 数据库菜单数据生成html ul列表树
1591
+ // const data = { trees: [ { "tid": 6, "id": 1, "name": "管理后台菜单", "open": true, "isParent": true, "isPublic": false, "checked": false }, { "tid": 14, "id": 277,...
1592
+ static menu(trees, isIgnoreTop) {
1593
+ let html = "";
1594
+ const build = function(trees, level, pid) {
1595
+ let result = "";
1596
+ ++level;
1597
+ for ( let i = 0; i < trees.length; i++) {
1598
+ const tree = trees[i];
1599
+
1600
+ let link = "#";
1601
+ if (tree.link)
1602
+ link = tree.link;
1603
+ // link = "../" + tree.link;
1604
+ if (!tree.pId && level === 0) {
1605
+ if (isIgnoreTop) {
1606
+ //不显示第一层菜单
1607
+ result = build(trees, level, tree.id);
1608
+ } else {
1609
+ let html = build(trees, level, tree.id),
1610
+ hash = tree.hash ? " data-hash='" + tree.hash + "' " : " ",
1611
+ actionId = tree.actionId ? " id='" + tree.actionId + "' " : " ";
1612
+
1613
+ if (html) {
1614
+ html = "<ul class='sub'>" + html + "</ul>";
1615
+ }
1616
+ result += "<li class='sub-menu'>" +
1617
+ "<a" + hash + actionId + "href='" + link + "'><span>" + tree.name + "</span></a>" +
1618
+ html + "</li>";
1619
+
1620
+ }
1621
+ } else if (tree.pId === pid) {
1622
+ let html = "";
1623
+ if (tree.isParent) {//返回数据为节点即不再遍历
1624
+ html = build(trees, level, tree.id);
1625
+ if (html)
1626
+ html = "<ul class='sub'>" + html + "</ul>";
1627
+ }
1628
+
1629
+ let icon = "";//第二层名称前加一个图标
1630
+ if (level === 1)
1631
+ icon = "<i class='" + tree.icon + "'></i>";
1632
+
1633
+ let hash = tree.hash ? " data-hash='" + tree.hash + "' " : " ",
1634
+ actionId = tree.actionId ? " id='" + tree.actionId + "' " : " ";
1635
+
1636
+ result += "<li class='sub-menu'>" +
1637
+ "<a" + hash + actionId + "href='" + link + "'>" +
1638
+ icon +
1639
+ "<span>" + tree.name + "</span>" +
1640
+ "</a>" +
1641
+ html +
1642
+ "</li>";
1643
+ }
1644
+ }
1645
+ return result;
1646
+ }
1647
+ let h = "";
1648
+ if (trees)
1649
+ h = build(trees, -1);
1650
+ return html + h;
1651
+ }
1652
+
1653
+ /**
1654
+ * 数据库普通的数据列表转换成有层次的数组
1655
+ * <pre>
1656
+ //菜单数据节点,如:
1657
+ //a ----------------
1658
+ //b ----------------
1659
+ //根据子父字段数据 形成 节点嵌套,如:
1660
+ //a ------------
1661
+ // b ---------------
1662
+ // c ---------------
1663
+ //d ----------------
1664
+ //e ----------------
1665
+ // f ------------
1666
+
1667
+ b.l(menu2Tree(data.trees, 1, 1)); //数据和上一个方法相同
1668
+ * </pre>
1669
+ **/
1670
+ static menu2Tree(menus, pid, activeid) {
1671
+ let children = [];
1672
+ let m = menus;
1673
+ menus.forEach(function(value) {
1674
+ if (value.pId === pid) {
1675
+ value.isactive = ("a" + value.id) === activeid;
1676
+ children.push(value);
1677
+ if (value.isParent) {
1678
+ value.children = b.menu2Tree(m, value.id);
1679
+ }
1680
+ }
1681
+ });
1682
+ return children;
1683
+ }
1684
+
1685
+ /**
1686
+ * 包含搜索按钮删除按钮的搜索框
1687
+ * <pre>
1688
+ <div class="fm-search">
1689
+ <span class="bi bi-search"></span>
1690
+ <input type="text" placeholder="检索你想找的内容">
1691
+ <span class="bi bi-trash3"></span>
1692
+ </div>
1693
+
1694
+ import 'istyle/src/css/form/form.css'
1695
+ b.search(function(txt) {
1696
+ if (txt) console.log(txt);
1697
+ });
1698
+ * </pre>
1699
+ **/
1700
+ static search(fun) {
1701
+ const mySearch = b(".fm-search"),
1702
+ myInput = b("input", mySearch),
1703
+ myFind = b("span:eq(0)", mySearch),
1704
+ myClear = b("span:eq(1)", mySearch);
1705
+ myInput.on("change",(e) => {
1706
+ const myTarget = b(e.currentTarget);
1707
+ if (myTarget.val() !== "")
1708
+ myTarget.next().css("opacity", "1").css("visibility", "visible");
1709
+ else
1710
+ myTarget.next().css("opacity", "0").css("visibility", "hidden");
1711
+ });
1712
+ if (myInput.val() !== "")
1713
+ myInput.next().css("opacity", "1").css("visibility", "visible");
1714
+ myClear.on("click", (e) => {
1715
+ const myTarget = b(e.currentTarget);
1716
+ myTarget.css("opacity", "0").css("visibility", "hidden");
1717
+ myTarget.prev().val("");
1718
+ });
1719
+ myFind.on("click", (e) => {
1720
+ const myTarget = b(e.currentTarget);
1721
+ if(fun)
1722
+ fun(myTarget.next().val());
1723
+ });
1724
+ }
1725
+
1726
+ // static plugin(pluginName, pluginFunction) {
1727
+ // // 确保 Base.fn 是一个对象,如果不是,你可能需要修正这一点
1728
+ // if (typeof Base.fn === 'object' && Base.fn !== null) {
1729
+ // // 使用 Object.defineProperty 添加属性到 Base.fn
1730
+ // Object.defineProperty(Base.fn, pluginName, {
1731
+ // value: pluginFunction, // 设置属性的值为插件函数
1732
+ // enumerable: false, // 默认情况下,我们可能不希望这个属性是可枚举的
1733
+ // writable: false, // 我们可能不希望这个属性被重写
1734
+ // configurable: false // 我们可能不希望这个属性被删除或重新配置
1735
+ // // 注意:writable 和 configurable 设置为 false 可能会导致在严格模式下无法删除该属性
1736
+ // });
1737
+ // } else {
1738
+ // throw new Error('Base.fn is not an object or is null');
1739
+ // }
1740
+ // }
1741
+
1742
+ // 2.3 私有静态方法
1743
+
1744
+ // 用于从 data-* 属性中获取数据
1745
+ static dataAttr = function(elem, key) {
1746
+ let name = "data-" + key;
1747
+ return elem.getAttribute(name) ? elem.getAttribute(name) : undefined;
1748
+ }
1749
+
1750
+ // console.log(b("> div", ".container")); 模式选择器
1751
+ static contextQuerySelector(selector, context) {
1752
+ if (selector.startsWith('>')) {
1753
+ return Array.from(context.querySelectorAll(selector.substring(1))).filter(function(e) {
1754
+ return e.parentNode === context;
1755
+ });
1756
+ // } else if (selector && selector.trim() === "option:selected") {
1757
+ // selectElement.options[selectElement.selectedIndex];
1758
+ } else {
1759
+ const nodes = context.querySelectorAll( selector );
1760
+ if (nodes.length === 0) {
1761
+ return Array.from( document.querySelectorAll( selector ) )
1762
+ } else {
1763
+ return Array.from( nodes )
1764
+ }
1765
+ }
1766
+ }
1767
+
1768
+ // 判断是否为 html标签:eq(数字) 格式
1769
+ static isEqSelector(str) {
1770
+ const regex = /^[\w-]+:eq\((\d+)\)$/;
1771
+ const match = str.match(regex);
1772
+ return match !== null && match[1] !== undefined;
1773
+ }
1774
+
1775
+
1776
+ // 2.4 静态属性
1777
+ // 生成缓存随机名称
1778
+ static expando = "base" + ("" + Math.random()).replace(/\D/g, "");
1779
+ static cache = { };
1780
+
1781
+ static build(selector, context) {
1782
+ return new Base(selector, context);
1783
+ }
1784
+
1785
+ }
1786
+
1787
+
1788
+ Base.build.extend = Base.extend;//参数继承
1789
+ Base.build.camelCase = Base.camelCase;//字符串驼峰化
1790
+ Base.build.l = Base.l;//打印
1791
+ Base.build.getParam = Base.getParam;//获取url参数
1792
+ Base.build.toRound = Base.toRound;//四舍五入
1793
+ Base.build.isNull = Base.isNull;//是否为空判断
1794
+ Base.build.setDefault = Base.setDefault;//默认值设置
1795
+ Base.build.same = Base.same;//获取两个数组中的相同值
1796
+ Base.build.different = Base.different;//获取两个数组中的不同值
1797
+ Base.build.strValidation = Base.strValidation;//表单字符串验证
1798
+ Base.build.move = Base.move;//页面内缓慢移动
1799
+ Base.build.keys = Base.keys;//常用键盘按键
1800
+ Base.build.hotkey = Base.hotkey;//常用快捷键事件绑定
1801
+ Base.build.isHtmlTag = Base.isHtmlTag;//常用快捷键事件绑定
1802
+ Base.build.isObject = Base.isObject;//判断变量是否为对象
1803
+ Base.build.plugin = Base.plugin;//支持扩展插件,声明的插件或者方法有有警告不提示,直接使用b['test'] = test;绑定
1804
+ Base.build.ajax = Base.ajax;//ajax异步请求
1805
+ Base.build.setCookie = Base.setCookie;//设置cookie
1806
+ Base.build.getCookie = Base.getCookie;//获取cookie
1807
+ Base.build.removeCookie = Base.removeCookie;//删除cookie
1808
+ Base.build.menu = Base.menu;//数据库菜单数据生成ul列表树
1809
+ Base.build.menu2Tree = Base.menu2Tree;//数据库普通的数据列表转换成有层次的数组
1810
+ Base.build.search = Base.search;//包含搜索按钮删除按钮的搜索框
1811
+ const b = Base.build;
1812
+
1813
+ Base.fn = Base.prototype; // 简化对原型的引用,eg:Base.fn.extend('testFun', testFun);
1814
+ // Base.prototype.constructor = Base;
1815
+ // Base.fn.plugin = function(pluginName, pluginFunction) {
1816
+ // Base.fn[pluginName] = pluginFunction;
1817
+ // };
1818
+
1819
+ /* ========================================================================
1820
+ * 其他常用方法,原生JS方法重写等
1821
+ * ======================================================================== */
1822
+
1823
+ /**
1824
+ * 时间格式化
1825
+ * <pre>
1826
+ new Date().format("yyyy-MM-dd hh:mm:ss")
1827
+ * </pre>
1828
+ **/
1829
+ Date.prototype.format = function(fmt) {
1830
+ let o = {
1831
+ "M+" : this.getMonth() + 1,
1832
+ "d+" : this.getDate(),
1833
+ "h+" : this.getHours(),
1834
+ "m+" : this.getMinutes(),
1835
+ "s+" : this.getSeconds(),
1836
+ "q+" : Math.floor((this.getMonth() + 3) / 3),
1837
+ "S" : this.getMilliseconds()
1838
+ };
1839
+ if (/(y+)/.test(fmt))
1840
+ fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
1841
+ for ( let k in o)
1842
+ if (new RegExp("(" + k + ")").test(fmt))
1843
+ fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
1844
+ return fmt;
1845
+ }
1846
+
1847
+ /**
1848
+ * 数组根据下标删除扩展,返回执行完数组长度
1849
+ * <pre>
1850
+ let array = ['a', 'b', 'c', 'd']
1851
+ eg1: array.remove(0);//删除第一个元素
1852
+ eg2: array.remove(-1);//删除倒数第一个元素
1853
+ eg3: array.remove(0, 2);///删除数组中下标为0-2的元素(3个)
1854
+ * </pre>
1855
+ **/
1856
+ Array.prototype.remove = function(from, to) {
1857
+ let rest = this.slice((to || from) + 1 || this.length);
1858
+ this.length = from < 0 ? this.length + from : from;
1859
+ return this.push.apply(this, rest);
1860
+ }
1861
+
1862
+ /**
1863
+ * 删除重复元素
1864
+ * <pre>
1865
+ let arr = [1,2];
1866
+ let arr2 = arr.concat(1,2,3,1)
1867
+ arr2.unique()
1868
+ * </pre>
1869
+ **/
1870
+ Array.prototype.unique = function () {
1871
+ let temp = [];
1872
+ this.sort();
1873
+ for(let i = 0; i < this.length; i++) {
1874
+ if(this[i] === this[i+1]) {
1875
+ continue;
1876
+ }
1877
+ temp[temp.length]=this[i];
1878
+ }
1879
+ return temp;
1880
+ }
1881
+
1882
+
1883
+ export { Base }
1884
+ export default b;