multitabs.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. //Make sure jQuery has been loaded
  2. if (typeof jQuery === "undefined") {
  3. throw new Error("MultiTabs requires jQuery");
  4. }((function ($) {
  5. "use strict";
  6. var NAMESPACE, tabIndex; //variable
  7. var MultiTabs, handler, getTabIndex, isExtUrl, sumDomWidth, trimText, supportStorage; //function
  8. var defaultLayoutTemplates, defaultInit; //default variable
  9. NAMESPACE = '.multitabs'; // namespace for on() function
  10. /**
  11. * splice namespace for on() function, and bind it
  12. * @param $selector jQuery selector
  13. * @param event event
  14. * @param childSelector child selector (string), same as on() function
  15. * @param fn function
  16. * @param skipNS bool. If true skip splice namespace
  17. */
  18. handler = function ($selector, event, childSelector, fn, skipNS) {
  19. var ev = skipNS ? event : event.split(' ').join(NAMESPACE + ' ') + NAMESPACE;
  20. $selector.off(ev, childSelector, fn).on(ev, childSelector, fn);
  21. };
  22. /**
  23. * get index for tab
  24. * @param content content type, for 'main' tab just can be 1
  25. * @param capacity capacity of tab, except 'main' tab
  26. * @returns int return index
  27. */
  28. getTabIndex = function (content, capacity) {
  29. if (content === 'main') return 0;
  30. capacity = capacity || 8; //capacity of maximum tab quantity, the tab will be cover if more than it
  31. tabIndex = tabIndex || 0;
  32. tabIndex++;
  33. tabIndex = tabIndex % capacity;
  34. return tabIndex;
  35. };
  36. /**
  37. * trim text, remove the extra space, and trim text with maxLength, add '...' after trim.
  38. * @param text the text need to trim
  39. * @param maxLength max length for text
  40. * @returns {string} return trimed text
  41. */
  42. trimText = function (text, maxLength) {
  43. maxLength = maxLength || $.fn.multitabs.defaults.navTab.maxTitleLength;
  44. var words = (text + "").split(' ');
  45. var t = '';
  46. for (var i = 0; i < words.length; i++) {
  47. var w = $.trim(words[i]);
  48. t += w ? (w + ' ') : '';
  49. }
  50. if (t.length > maxLength) {
  51. t = t.substr(0, maxLength);
  52. t += '...'
  53. }
  54. return t;
  55. };
  56. supportStorage = function (is_cache) {
  57. return !(sessionStorage === undefined) && is_cache;
  58. }
  59. /**
  60. * Calculate the total width
  61. * @param JqueryDomObjList the object list for calculate
  62. * @returns {number} return total object width (int)
  63. */
  64. sumDomWidth = function (JqueryDomObjList) {
  65. var width = 0;
  66. $(JqueryDomObjList).each(function () {
  67. width += $(this).outerWidth(true)
  68. });
  69. return width
  70. };
  71. /**
  72. * Judgment is external URL
  73. * @param url URL for judgment
  74. * @returns {boolean} external URL return true, local return false
  75. */
  76. isExtUrl = function (url) {
  77. var absUrl = (function (url) {
  78. var a = document.createElement('a');
  79. a.href = url;
  80. return a.href;
  81. })(url);
  82. var webRoot = window.location.protocol + '//' + window.location.host + '/';
  83. var urlRoot = absUrl.substr(0, webRoot.length);
  84. return (!(urlRoot === webRoot));
  85. };
  86. /**
  87. * Layout Templates
  88. */
  89. defaultLayoutTemplates = {
  90. /**
  91. * Main Layout
  92. */
  93. default: '<div class="mt-wrapper {mainClass}" style="height: 100%;" >' +
  94. '<div class="mt-nav-bar {navClass}" style="background-color: {backgroundColor};">' +
  95. '<div class="mt-nav mt-nav-tools-left">' +
  96. '<ul class="nav {nav-tabs}">' +
  97. '<li class="mt-move-left"><a><i class="mdi mdi-skip-backward"></i></a></li>' +
  98. '</ul>' +
  99. '</div>' +
  100. '<nav class="mt-nav mt-nav-panel">' +
  101. '<ul class="nav {nav-tabs}"></ul>' +
  102. '</nav>' +
  103. '<div class="mt-nav mt-nav-tools-right">' +
  104. '<ul class="nav {nav-tabs}">' +
  105. '<li class="mt-move-right"><a><i class="mdi mdi-skip-forward"></i></a></li>' +
  106. '<li class="mt-dropdown dropdown">' +
  107. '<a href="#" class="dropdown-toggle" data-toggle="dropdown">{dropdown}<span class="caret"></span></a>' +
  108. '<ul role="menu" class="dropdown-menu dropdown-menu-right">' +
  109. '<li class="mt-show-actived-tab"><a>{showActivedTab}</a></li>' +
  110. '<li class="divider"></li>' +
  111. '<li class="mt-close-all-tabs"><a>{closeAllTabs}</a></li>' +
  112. '<li class="mt-close-other-tabs"><a>{closeOtherTabs}</a></li>' +
  113. '</ul>' +
  114. '</li>' +
  115. '</ul>' +
  116. '</div>' +
  117. '</div>' +
  118. '<div class="tab-content mt-tab-content " > </div>' +
  119. '</div>',
  120. classic: '<div class="mt-wrapper {mainClass}" style="height: 100%;" >' +
  121. '<div class="mt-nav-bar {navClass}" style="background-color: {backgroundColor};">' +
  122. '<nav class="mt-nav mt-nav-panel">' +
  123. '<ul class="nav {nav-tabs}"> </ul>' +
  124. '</nav>' +
  125. '<div class="mt-nav mt-nav-tools-right">' +
  126. '<ul class="nav {nav-tabs}">' +
  127. '<li class="mt-dropdown dropdown">' +
  128. '<a href="#" class="dropdown-toggle" data-toggle="dropdown">{dropdown}<span class="caret"></span></a>' +
  129. '<ul role="menu" class="mt-hidden-list dropdown-menu dropdown-menu-right"></ul>' +
  130. '</li>' +
  131. '</ul>' +
  132. '</div>' +
  133. '</div>' +
  134. '<div class="tab-content mt-tab-content " > </div>' +
  135. '</div>',
  136. simple: '<div class="mt-wrapper {mainClass}" style="height: 100%;" >' +
  137. '<div class="mt-nav-bar {navClass}" style="background-color: {backgroundColor};">' +
  138. '<nav class="mt-nav mt-nav-panel">' +
  139. '<ul class="nav {nav-tabs}"> </ul>' +
  140. '</nav>' +
  141. '</div>' +
  142. '<div class="tab-content mt-tab-content " > </div>' +
  143. '</div>',
  144. navTab: '<a data-id="{navTabId}" class="mt-nav-tab" data-type="{type}" data-index="{index}" data-url="{url}">{title}</a>',
  145. closeBtn: ' <i class="mt-close-tab mdi mdi-close" style="{style}"></i>',
  146. ajaxTabPane: '<div id="{tabPaneId}" class="tab-pane {class}">{content}</div>',
  147. iframeTabPane: '<iframe id="{tabPaneId}" class="tab-pane {class}" width="100%" height="100%" frameborder="0" src="" seamless></iframe>'
  148. };
  149. /**
  150. * Default init page
  151. * @type {*[]}
  152. */
  153. defaultInit = [{ //default tabs in initial;
  154. type: 'main', //default is info;
  155. title: 'main', //default title;
  156. content: '<h1>Demo page</h1><h2>Welcome to use bootstrap multi-tabs :) </h2>' //default content
  157. }];
  158. /**
  159. * multitabs constructor
  160. * @param element Primary container
  161. * @param options options
  162. * @constructor
  163. */
  164. MultiTabs = function (element, options) {
  165. var self = this;
  166. self.$element = $(element);
  167. self._init(options)._listen()._final();
  168. };
  169. /**
  170. * MultiTabs's function
  171. */
  172. MultiTabs.prototype = {
  173. /**
  174. * constructor
  175. */
  176. constructor: MultiTabs,
  177. /**
  178. * create tab and return this.
  179. * @param obj the obj to trigger multitabs
  180. * @param active if true, active tab after create
  181. * @returns this Chain structure.
  182. */
  183. create: function (obj, active) {
  184. var options = this.options;
  185. var param, $navTab;
  186. if (!(param = this._getParam(obj))) {
  187. return this; //return multitabs obj when is invaid obj
  188. }
  189. $navTab = this._exist(param)
  190. if ($navTab && !param.refresh) {
  191. this.active($navTab);
  192. return this;
  193. }
  194. param.active = !param.active ? active : param.active;
  195. //nav tab create
  196. $navTab = this._createNavTab(param);
  197. //tab-pane create
  198. this._createTabPane(param);
  199. //add tab to storage
  200. this._storage(param.did, param);
  201. if (param.active) {
  202. this.active($navTab);
  203. }
  204. return this;
  205. },
  206. /**
  207. * Create tab pane
  208. * @param param
  209. * @param index
  210. * @returns {*|{}}
  211. * @private
  212. */
  213. _createTabPane: function (param) {
  214. var self = this,
  215. $el = self.$element;
  216. $el.tabContent.append(self._getTabPaneHtml(param));
  217. return $el.tabContent.find('#' + param.did);
  218. },
  219. /**
  220. * get tab pane html
  221. * @param param
  222. * @param index
  223. * @returns {string}
  224. * @private
  225. */
  226. _getTabPaneHtml: function (param) {
  227. var self = this,
  228. options = self.options;
  229. if (!param.content && param.iframe) {
  230. return defaultLayoutTemplates.iframeTabPane
  231. .replace('{class}', options.content.iframe.class)
  232. .replace('{tabPaneId}', param.did);
  233. } else {
  234. return defaultLayoutTemplates.ajaxTabPane
  235. .replace('{class}', options.content.ajax.class)
  236. .replace('{tabPaneId}', param.did)
  237. .replace('{content}', param.content);
  238. }
  239. },
  240. /**
  241. * create nav tab
  242. * @param param
  243. * @param index
  244. * @returns {*|{}}
  245. * @private
  246. */
  247. _createNavTab: function (param) {
  248. var self = this,
  249. $el = self.$element;
  250. var navTabHtml = self._getNavTabHtml(param);
  251. var $navTabLi = $el.navPanelList.find('a[data-type="' + param.type + '"][data-index="' + param.index + '"]').parent('li');
  252. if ($navTabLi.length) {
  253. $navTabLi.html(navTabHtml);
  254. self._getTabPane($navTabLi.find('a:first')).remove(); //remove old content pane directly
  255. } else {
  256. $el.navPanelList.append('<li>' + navTabHtml + '</li>');
  257. }
  258. return $el.navPanelList.find('a[data-type="' + param.type + '"][data-index="' + param.index + '"]:first');
  259. },
  260. /**
  261. * get nav tab html
  262. * @param param
  263. * @param index
  264. * @returns {string}
  265. * @private
  266. */
  267. _getNavTabHtml: function (param) {
  268. var self = this,
  269. options = self.options;
  270. var closeBtnHtml, display;
  271. display = options.nav.showCloseOnHover ? '' : 'display:inline;';
  272. closeBtnHtml = (param.type === 'main') ? '' : defaultLayoutTemplates.closeBtn.replace('{style}', display); //main content can not colse.
  273. return defaultLayoutTemplates.navTab
  274. .replace('{index}', param.index)
  275. .replace('{navTabId}', param.did)
  276. .replace('{url}', param.url)
  277. .replace('{title}', param.title)
  278. .replace('{type}', param.type) +
  279. closeBtnHtml;
  280. },
  281. /**
  282. * generate tab pane's id
  283. * @param param
  284. * @param index
  285. * @returns {string}
  286. * @private
  287. */
  288. _generateId: function (param) {
  289. return 'multitabs_' + param.type + '_' + param.index;
  290. },
  291. /**
  292. * active navTab
  293. * @param navTab
  294. * @returns self Chain structure.
  295. */
  296. active: function (navTab) {
  297. var self = this,
  298. $el = self.$element;
  299. var $navTab = self._getNavTab(navTab),
  300. $tabPane = self._getTabPane($navTab),
  301. $prevActivedTab = $el.navPanelList.find('li.active:first a');
  302. var prevNavTabParam = $prevActivedTab.length ? self._getParam($prevActivedTab) : {};
  303. var navTabParam = $navTab.length ? self._getParam($navTab) : {};
  304. //change storage active status
  305. var storage = self._storage();
  306. if (storage[prevNavTabParam.id]) {
  307. storage[prevNavTabParam.id].active = false;
  308. }
  309. if (storage[navTabParam.id]) {
  310. storage[navTabParam.id].active = true;
  311. }
  312. self._resetStorage(storage);
  313. //active navTab and tabPane
  314. $prevActivedTab.parent('li').removeClass('active');
  315. $navTab.parent('li').addClass('active');
  316. self._fixTabPosition($navTab);
  317. self._getTabPane($prevActivedTab).removeClass('active');
  318. $tabPane.addClass('active');
  319. self._fixTabContentLayout($tabPane);
  320. //fill tab pane
  321. self._fillTabPane($tabPane, navTabParam);
  322. return self;
  323. },
  324. /**
  325. * fill tab pane
  326. * @private
  327. */
  328. _fillTabPane: function (tabPane, param) {
  329. var self = this,
  330. options = self.options;
  331. var $tabPane = $(tabPane);
  332. //if navTab-pane empty, load content
  333. if (!$tabPane.html()) {
  334. if ($tabPane.is('iframe')) {
  335. if (!$tabPane.attr('src')) {
  336. $tabPane.attr('src', param.url);
  337. }
  338. } else {
  339. $.ajax({
  340. url: param.url,
  341. dataType: "html",
  342. success: function (callback) {
  343. $tabPane.html(options.content.ajax.success(callback));
  344. },
  345. error: function (callback) {
  346. $tabPane.html(options.content.ajax.error(callback));
  347. }
  348. });
  349. }
  350. }
  351. },
  352. /**
  353. * move left
  354. * @return self
  355. */
  356. moveLeft: function () {
  357. var self = this,
  358. $el = self.$element,
  359. navPanelListMarginLeft = Math.abs(parseInt($el.navPanelList.css("margin-left"))),
  360. navPanelWidth = $el.navPanel.outerWidth(true),
  361. sumTabsWidth = sumDomWidth($el.navPanelList.children('li')),
  362. leftWidth = 0,
  363. marginLeft = 0,
  364. $navTabLi;
  365. if (sumTabsWidth < navPanelWidth) {
  366. return self
  367. } else {
  368. $navTabLi = $el.navPanelList.children('li:first');
  369. while ((marginLeft + $navTabLi.width()) <= navPanelListMarginLeft) {
  370. marginLeft += $navTabLi.outerWidth(true);
  371. $navTabLi = $navTabLi.next();
  372. }
  373. marginLeft = 0;
  374. if (sumDomWidth($navTabLi.prevAll()) > navPanelWidth) {
  375. while (((marginLeft + $navTabLi.width()) < navPanelWidth) && $navTabLi.length > 0) {
  376. marginLeft += $navTabLi.outerWidth(true);
  377. $navTabLi = $navTabLi.prev();
  378. }
  379. leftWidth = sumDomWidth($navTabLi.prevAll());
  380. }
  381. }
  382. $el.navPanelList.animate({
  383. marginLeft: 0 - leftWidth + "px"
  384. }, "fast");
  385. return self;
  386. },
  387. /**
  388. * move right
  389. * @return self
  390. */
  391. moveRight: function () {
  392. var self = this,
  393. $el = self.$element,
  394. navPanelListMarginLeft = Math.abs(parseInt($el.navPanelList.css("margin-left"))),
  395. navPanelWidth = $el.navPanel.outerWidth(true),
  396. sumTabsWidth = sumDomWidth($el.navPanelList.children('li')),
  397. leftWidth = 0,
  398. $navTabLi, marginLeft;
  399. if (sumTabsWidth < navPanelWidth) {
  400. return self;
  401. } else {
  402. $navTabLi = $el.navPanelList.children('li:first');
  403. marginLeft = 0;
  404. while ((marginLeft + $navTabLi.width()) <= navPanelListMarginLeft) {
  405. marginLeft += $navTabLi.outerWidth(true);
  406. $navTabLi = $navTabLi.next();
  407. }
  408. marginLeft = 0;
  409. while (((marginLeft + $navTabLi.width()) < navPanelWidth) && $navTabLi.length > 0) {
  410. marginLeft += $navTabLi.outerWidth(true);
  411. $navTabLi = $navTabLi.next();
  412. }
  413. leftWidth = sumDomWidth($navTabLi.prevAll());
  414. if (leftWidth > 0) {
  415. $el.navPanelList.animate({
  416. marginLeft: 0 - leftWidth + "px"
  417. }, "fast");
  418. }
  419. }
  420. return self;
  421. },
  422. /**
  423. * close navTab
  424. * @param navTab
  425. * @return self Chain structure.
  426. */
  427. close: function (navTab) {
  428. var self = this,
  429. $tabPane;
  430. var $navTab = self._getNavTab(navTab),
  431. $navTabLi = $navTab.parent('li');
  432. $tabPane = self._getTabPane($navTab);
  433. //close unsave tab confirm
  434. if ($navTabLi.length &&
  435. $tabPane.length &&
  436. $tabPane.hasClass('unsave') &&
  437. !self._unsaveConfirm()) {
  438. return self;
  439. }
  440. if ($navTabLi.hasClass("active")) {
  441. var $nextLi = $navTabLi.next("li:first"),
  442. $prevLi = $navTabLi.prev("li:last");
  443. if ($nextLi.size()) {
  444. self.active($nextLi);
  445. } else if ($prevLi.size()) {
  446. self.active($prevLi);
  447. }
  448. }
  449. self._delStorage($navTab.attr('data-id')); //remove tab from session storage
  450. $navTabLi.remove();
  451. $tabPane.remove();
  452. return self;
  453. },
  454. /**
  455. * close others tab
  456. * @return self Chain structure.
  457. */
  458. closeOthers: function () {
  459. var self = this,
  460. $el = self.$element;
  461. $el.navPanelList.find('li:not(.active)').find('a:not([data-type="main"])').each(function () {
  462. var $navTab = $(this);
  463. self._delStorage($navTab.attr('data-id')); //remove tab from session storage
  464. self._getTabPane($navTab).remove(); //remove tab-content
  465. $navTab.parent('li').remove(); //remove navtab
  466. });
  467. $el.navPanelList.css("margin-left", "0");
  468. return self;
  469. },
  470. /**
  471. * focus actived tab
  472. * @return self Chain structure.
  473. */
  474. showActive: function () {
  475. var self = this,
  476. $el = self.$element;
  477. var navTab = $el.navPanelList.find('li.active:first a');
  478. self._fixTabPosition(navTab);
  479. return self;
  480. },
  481. /**
  482. * close all tabs, (except main tab)
  483. * @return self Chain structure.
  484. */
  485. closeAll: function () {
  486. var self = this,
  487. $el = self.$element;
  488. $el.navPanelList.find('a:not([data-type="main"])').each(function () {
  489. var $navTab = $(this);
  490. self._delStorage($navTab.attr('data-id')); //remove tab from session storage
  491. self._getTabPane($navTab).remove(); //remove tab-content
  492. $navTab.parent('li').remove(); //remove navtab
  493. });
  494. self.active($el.navPanelList.find('a[data-type="main"]:first').parent('li'));
  495. return self;
  496. },
  497. /**
  498. * init function
  499. * @param options
  500. * @returns self
  501. * @private
  502. */
  503. _init: function (options) {
  504. var self = this,
  505. $el = self.$element;
  506. $el.html(defaultLayoutTemplates[options.nav.layout]
  507. .replace('{mainClass}', options.class)
  508. .replace('{navClass}', options.nav.class)
  509. .replace(/\{nav-tabs\}/g, options.nav.style)
  510. .replace(/\{backgroundColor\}/g, options.nav.backgroundColor)
  511. .replace('{dropdown}', options.language.nav.dropdown)
  512. .replace('{showActivedTab}', options.language.nav.showActivedTab)
  513. .replace('{closeAllTabs}', options.language.nav.closeAllTabs)
  514. .replace('{closeOtherTabs}', options.language.nav.closeOtherTabs)
  515. );
  516. $el.wrapper = $el.find('.mt-wrapper:first');
  517. $el.nav = $el.find('.mt-nav-bar:first');
  518. $el.navToolsLeft = $el.nav.find('.mt-nav-tools-left:first');
  519. $el.navPanel = $el.nav.find('.mt-nav-panel:first');
  520. $el.navPanelList = $el.nav.find('.mt-nav-panel:first ul');
  521. //$el.navTabMain = $('#multitabs_main_0');
  522. $el.navToolsRight = $el.nav.find('.mt-nav-tools-right:first');
  523. $el.tabContent = $el.find('.tab-content:first');
  524. //hide tab-header if maxTabs less than 1
  525. if (options.nav.maxTabs <= 1) {
  526. options.nav.maxTabs = 1;
  527. $el.nav.hide();
  528. }
  529. //set the nav-panel width
  530. var toolWidth = $el.nav.find('.mt-nav-tools-left:visible:first').width() + $el.nav.find('.mt-nav-tools-right:visible:first').width();
  531. $el.navPanel.css('width', 'calc(100% - ' + toolWidth + 'px)');
  532. self.options = options;
  533. return self;
  534. },
  535. /**
  536. * final funcion for after init Multitabs
  537. * @returns self
  538. * @private
  539. */
  540. _final: function () {
  541. var self = this,
  542. $el = self.$element,
  543. options = self.options,
  544. storage, init = options.init,
  545. param;
  546. if (supportStorage(options.cache)) {
  547. storage = self._storage();
  548. self._resetStorage({});
  549. $.each(storage, function (k, v) {
  550. self.create(v, false);
  551. })
  552. }
  553. if ($.isEmptyObject(storage)) {
  554. init = (!$.isEmptyObject(init) && init instanceof Array) ? init : defaultInit;
  555. for (var i = 0; i < init.length; i++) {
  556. param = self._getParam(init[i]);
  557. if (param) {
  558. self.create(param);
  559. }
  560. }
  561. }
  562. //if no any tab actived, active the main tab
  563. if (!$el.navPanelList.children('li.active').length) {
  564. self.active($el.navPanelList.find('[data-type="main"]:first'));
  565. }
  566. return self;
  567. },
  568. /**
  569. * bind action
  570. * @return self
  571. * @private
  572. */
  573. _listen: function () {
  574. var self = this,
  575. $el = self.$element,
  576. options = self.options;
  577. //create tab
  578. handler($(document), 'click', options.selector, function () {
  579. self.create(this, true);
  580. if (!$(this).parent().parent('ul').hasClass('dropdown-menu')) { // 20190402改,下拉菜单中的网址采用data-url,并且不阻止后面的动作
  581. return false; //Prevent the default selector action
  582. }
  583. });
  584. //active tab
  585. handler($el.nav, 'click', '.mt-nav-tab', function () {
  586. self.active(this);
  587. });
  588. //drag tab
  589. if (options.nav.draggable) {
  590. handler($el.navPanelList, 'mousedown', '.mt-nav-tab', function (event) {
  591. var $navTab = $(this),
  592. $navTabLi = $navTab.closest('li');
  593. var $prevNavTabLi = $navTabLi.prev();
  594. var dragMode = true,
  595. moved = false,
  596. isMain = ($navTab.data('type') === "main");
  597. var tmpId = 'mt_tmp_id_' + new Date().getTime(),
  598. navTabBlankHtml = '<li id="' + tmpId + '" class="mt-dragging" style="width:' + $navTabLi.outerWidth() + 'px; height:' + $navTabLi.outerHeight() + 'px;"><a style="width: 100%; height: 100%; "></a></li>';
  599. var abs_x = event.pageX - $navTabLi.offset().left + $el.nav.offset().left;
  600. $navTabLi.before(navTabBlankHtml);
  601. $navTabLi.addClass('mt-dragging mt-dragging-tab').css({
  602. 'left': event.pageX - abs_x + 'px'
  603. });
  604. $(document).on('mousemove', function (event) {
  605. if (dragMode && !isMain) {
  606. $navTabLi.css({
  607. 'left': event.pageX - abs_x + 'px'
  608. });
  609. $el.navPanelList.children('li:not(".mt-dragging")').each(function () {
  610. var leftWidth = $(this).offset().left + $(this).outerWidth() + 20; //20 px more for gap
  611. if (leftWidth > $navTabLi.offset().left) {
  612. if ($(this).next().attr('id') !== tmpId) {
  613. moved = true;
  614. $prevNavTabLi = $(this);
  615. $('#' + tmpId).remove();
  616. $prevNavTabLi.after(navTabBlankHtml);
  617. }
  618. return false;
  619. }
  620. });
  621. }
  622. }).on("selectstart", function () { //disable text selection
  623. if (dragMode) {
  624. return false;
  625. }
  626. }).on('mouseup', function () {
  627. if (dragMode) {
  628. $navTabLi.removeClass('mt-dragging mt-dragging-tab').css({'left': 'auto'});
  629. if (moved) {
  630. $prevNavTabLi.after($navTabLi);
  631. }
  632. $('#' + tmpId).remove();
  633. }
  634. dragMode = false;
  635. });
  636. });
  637. }
  638. //close tab
  639. handler($el.nav, 'click', '.mt-close-tab', function () {
  640. self.close($(this).closest('li'));
  641. return false; //Avoid possible BUG
  642. });
  643. //move left
  644. handler($el.nav, 'click', '.mt-move-left', function () {
  645. self.moveLeft();
  646. return false; //Avoid possible BUG
  647. });
  648. //move right
  649. handler($el.nav, 'click', '.mt-move-right', function () {
  650. self.moveRight();
  651. return false; //Avoid possible BUG
  652. });
  653. //show actived tab
  654. handler($el.nav, 'click', '.mt-show-actived-tab', function () {
  655. self.showActive();
  656. //return false; //Avoid possible BUG
  657. });
  658. //close all tabs
  659. handler($el.nav, 'click', '.mt-close-all-tabs', function () {
  660. self.closeAll();
  661. //return false; //Avoid possible BUG
  662. });
  663. //close other tabs
  664. handler($el.nav, 'click', '.mt-close-other-tabs', function () {
  665. self.closeOthers();
  666. //return false; //Avoid possible BUG
  667. });
  668. //fixed the nav-bar
  669. var navHeight = $el.nav.outerHeight();
  670. $el.tabContent.css('paddingTop', navHeight);
  671. if (options.nav.fixed) {
  672. handler($(window), 'scroll', function () {
  673. var scrollTop = $(this).scrollTop();
  674. scrollTop = scrollTop < ($el.wrapper.height() - navHeight) ? scrollTop + 'px' : 'auto';
  675. $el.nav.css('top', scrollTop);
  676. return false; //Avoid possible BUG
  677. });
  678. }
  679. //if layout === 'classic' show hide list in dropdown menu
  680. if (options.nav.layout === 'classic') {
  681. handler($el.nav, 'click', '.mt-dropdown:not(.open)', function () { //just trigger when dropdown not open.
  682. var list = self._getHiddenList();
  683. var $dropDown = $el.navToolsRight.find('.mt-hidden-list:first').empty();
  684. if (list) { //when list is not empty
  685. while (list.prevList.length) {
  686. $dropDown.append(list.prevList.shift().clone());
  687. }
  688. while (list.nextList.length) {
  689. $dropDown.append(list.nextList.shift().clone());
  690. }
  691. } else {
  692. $dropDown.append('<li>empty</li>');
  693. }
  694. // return false; //Avoid possible BUG
  695. });
  696. }
  697. return self;
  698. },
  699. /**
  700. * get the multitabs object's param
  701. * @param obj multitabs's object
  702. * @returns param param
  703. * @private
  704. */
  705. _getParam: function (obj) {
  706. if ($.isEmptyObject(obj)) {
  707. return false;
  708. }
  709. var self = this,
  710. options = self.options,
  711. param = {},
  712. $obj = $(obj),
  713. data = $obj.data();
  714. //content
  715. param.content = data.content || obj.content || '';
  716. if (!param.content.length) {
  717. //url
  718. param.url = data.url || obj.url || $obj.attr('href') || $obj.attr('url') || '';
  719. param.url = $.trim(decodeURIComponent(param.url.replace('#', '')));
  720. } else {
  721. param.url = '';
  722. }
  723. if (!param.url.length && !param.content.length) {
  724. return false;
  725. }
  726. //refresh
  727. param.refresh = data.hasOwnProperty('refresh') || obj.hasOwnProperty('refresh') || options.refresh;
  728. //iframe
  729. param.iframe = data.iframe || obj.iframe || isExtUrl(param.url) || options.iframe;
  730. //type
  731. param.type = data.type || obj.type || options.type;
  732. //title
  733. param.title = data.title || obj.title || $obj.text() || param.url.replace('http://', '').replace('https://', '') || options.language.nav.title;
  734. param.title = trimText(param.title, options.nav.maxTitleLength);
  735. //active
  736. param.active = data.active || obj.active || false;
  737. //index
  738. param.index = data.index || obj.index || getTabIndex(param.type, options.nav.maxTabs);
  739. //id
  740. param.did = data.did || obj.did || this._generateId(param);
  741. return param;
  742. },
  743. /**
  744. * session storage for tab list
  745. * @param key
  746. * @param param
  747. * @returns storage
  748. * @private
  749. */
  750. _storage: function (key, param) {
  751. if (supportStorage(this.options.cache)) {
  752. var storage = JSON.parse(sessionStorage.multitabs || '{}');
  753. if (!key) {
  754. return storage;
  755. }
  756. if (!param) {
  757. return storage[key];
  758. }
  759. storage[key] = param;
  760. sessionStorage.multitabs = JSON.stringify(storage);
  761. return storage;
  762. }
  763. return {};
  764. },
  765. /**
  766. * delete storage by key
  767. * @param key
  768. * @private
  769. */
  770. _delStorage: function (key) {
  771. if (supportStorage(this.options.cache)) {
  772. var storage = JSON.parse(sessionStorage.multitabs || '{}');
  773. if (!key) {
  774. return storage;
  775. }
  776. delete storage[key];
  777. sessionStorage.multitabs = JSON.stringify(storage);
  778. return storage;
  779. }
  780. return {};
  781. },
  782. /**
  783. * reset storage
  784. * @param storage
  785. * @private
  786. */
  787. _resetStorage: function (storage) {
  788. if (supportStorage(this.options.cache) && typeof storage === "object") {
  789. sessionStorage.multitabs = JSON.stringify(storage);
  790. }
  791. },
  792. /**
  793. * check if exist multitabs obj
  794. * @param param
  795. * @private
  796. */
  797. _exist: function (param) {
  798. if (!param || !param.url) {
  799. return false;
  800. }
  801. var self = this,
  802. $el = self.$element;
  803. var $navTab = $el.navPanelList.find('a[data-url="' + param.url + '"]:first');
  804. if ($navTab.length) {
  805. return $navTab;
  806. } else {
  807. return false;
  808. }
  809. },
  810. /**
  811. * get tab-pane from tab
  812. * @param tab
  813. * @returns {*}
  814. * @private
  815. */
  816. _getTabPane: function (navTab) {
  817. return $('#' + $(navTab).attr('data-id'));
  818. },
  819. /**
  820. * get real navTab in the panel list.
  821. * @param navTab
  822. * @returns navTab
  823. * @private
  824. */
  825. _getNavTab: function (navTab) {
  826. var self = this,
  827. $el = self.$element;
  828. var dataId = $(navTab).attr('data-id') || $(navTab).find('a').attr('data-id');
  829. return $el.navPanelList.find('a[data-id="' + dataId + '"]:first');
  830. },
  831. /**
  832. * fix nav navTab position
  833. * @param navTab
  834. * @private
  835. */
  836. _fixTabPosition: function (navTab) {
  837. var self = this,
  838. $el = self.$element,
  839. $navTabLi = $(navTab).parent('li'),
  840. tabWidth = $navTabLi.outerWidth(true),
  841. prevWidth = $navTabLi.prev().outerWidth(true),
  842. pprevWidth = $navTabLi.prev().prev().outerWidth(true),
  843. sumPrevWidth = sumDomWidth($navTabLi.prevAll()),
  844. sumNextWidth = sumDomWidth($navTabLi.nextAll()),
  845. navPanelWidth = $el.navPanel.outerWidth(true),
  846. sumTabsWidth = sumDomWidth($el.navPanelList.children('li')),
  847. leftWidth = 0;
  848. //all nav navTab's width no more than nav-panel's width
  849. if (sumTabsWidth < navPanelWidth) {
  850. leftWidth = 0
  851. } else {
  852. //when navTab and his right tabs sum width less or same as nav-panel, it means nav-panel can contain the navTab and his right tabs
  853. if ((prevWidth + tabWidth + sumNextWidth) <= navPanelWidth) {
  854. leftWidth = sumPrevWidth; //sum width of left part
  855. //add width from the left, calcular the maximum tabs can contained by nav-panel
  856. while ((sumTabsWidth - leftWidth + prevWidth) < navPanelWidth) {
  857. $navTabLi = $navTabLi.prev(); //change the left navTab
  858. leftWidth -= $navTabLi.outerWidth(); //reduce the left part width
  859. }
  860. } else { //nav-panel can not contain the navTab and his right tabs
  861. //when the navTab and his left part tabs's sum width more than nav-panel, all the width of 2 previous tabs's width set as the nav-panel margin-left.
  862. if ((sumPrevWidth + tabWidth) > navPanelWidth) {
  863. leftWidth = sumPrevWidth - prevWidth - pprevWidth
  864. }
  865. }
  866. }
  867. leftWidth = leftWidth > 0 ? leftWidth : 0; //avoid leftWidth < 0 BUG
  868. $el.navPanelList.animate({
  869. marginLeft: 0 - leftWidth + "px"
  870. }, "fast");
  871. },
  872. /**
  873. * hidden tab list
  874. * @returns hidden tab list, the prevList and nextList
  875. * @private
  876. */
  877. _getHiddenList: function () {
  878. var self = this,
  879. $el = self.$element,
  880. navPanelListMarginLeft = Math.abs(parseInt($el.navPanelList.css("margin-left"))),
  881. navPanelWidth = $el.navPanel.outerWidth(true),
  882. sumTabsWidth = sumDomWidth($el.navPanelList.children('li')),
  883. tabPrevList = [],
  884. tabNextList = [],
  885. $navTabLi, marginLeft;
  886. //all tab's width no more than nav-panel's width
  887. if (sumTabsWidth < navPanelWidth) {
  888. return false;
  889. } else {
  890. $navTabLi = $el.navPanelList.children('li:first');
  891. //overflow hidden left part
  892. marginLeft = 0;
  893. //from the first tab, add all left part hidden tabs
  894. while ((marginLeft + $navTabLi.width()) <= navPanelListMarginLeft) {
  895. marginLeft += $navTabLi.outerWidth(true);
  896. tabPrevList.push($navTabLi);
  897. $navTabLi = $navTabLi.next();
  898. }
  899. //overflow hidden right part
  900. if (sumTabsWidth > marginLeft) { //check if the right part have hidden tabs
  901. $navTabLi = $el.navPanelList.children('li:last');
  902. marginLeft = sumTabsWidth; //set margin-left as the Rightmost, and reduce one and one.
  903. while (marginLeft > (navPanelListMarginLeft + navPanelWidth)) {
  904. marginLeft -= $navTabLi.outerWidth(true);
  905. tabNextList.unshift($navTabLi); //add param from top
  906. $navTabLi = $navTabLi.prev();
  907. }
  908. }
  909. return {
  910. prevList: tabPrevList,
  911. nextList: tabNextList
  912. };
  913. }
  914. },
  915. /**
  916. * check if tab-pane is iframe, and add/remove class
  917. * @param tabPane
  918. * @private
  919. */
  920. _fixTabContentLayout: function (tabPane) {
  921. var $tabPane = $(tabPane);
  922. if ($tabPane.is('iframe')) {
  923. $('body').addClass('full-height-layout');
  924. /** fix chrome croll disappear bug **/
  925. $tabPane.css("height", "99%");
  926. window.setTimeout(function () {
  927. $tabPane.css("height", "100%");
  928. }, 0);
  929. } else {
  930. $('body').removeClass('full-height-layout');
  931. }
  932. },
  933. };
  934. /**
  935. * Entry function
  936. * @param option
  937. */
  938. $.fn.multitabs = function (option, id) {
  939. var self = $(this),
  940. did = id ? id : 'multitabs',
  941. multitabs = $(document).data(did),
  942. options = typeof option === 'object' && option,
  943. opts;
  944. if (!multitabs) {
  945. opts = $.extend(true, {}, $.fn.multitabs.defaults, options, self.data());
  946. opts.nav.style = (opts.nav.style === 'nav-pills') ? 'nav-pills' : 'nav-tabs';
  947. multitabs = new MultiTabs(this, opts);
  948. $(document).data(did, multitabs);
  949. }
  950. return $(document).data(did);
  951. };
  952. /**
  953. * Default Options
  954. * @type {}
  955. */
  956. $.fn.multitabs.defaults = {
  957. selector: '.multitabs', //selector text to trigger multitabs.
  958. iframe: false, //Global iframe mode, default is false, is the auto mode (for the self page, use ajax, and the external, use iframe)
  959. cache: false,
  960. class: '', //class for whole multitabs
  961. type: 'info', //change the info content name, is not necessary to change.
  962. init: [],
  963. refresh: false,
  964. nav: {
  965. backgroundColor: '#f5f5f5', //default nav-bar background color
  966. class: '', //class of nav
  967. draggable: true, //nav tab draggable option
  968. fixed: false, //fixed the nav-bar
  969. layout: 'default', //it can be 'default', 'classic' (all hidden tab in dropdown list), and simple
  970. maxTabs: 15, //Max tabs number (without counting main tab), when is 1, hide the whole nav
  971. maxTitleLength: 25, //Max title length of tab
  972. showCloseOnHover: true, //while is true, show close button in hover, if false, show close button always
  973. style: 'nav-tabs' //can be nav-tabs or nav-pills
  974. },
  975. content: {
  976. ajax: {
  977. class: '', //Class for ajax tab-pane
  978. error: function (htmlCallBack) {
  979. //modify html and return
  980. return htmlCallBack;
  981. },
  982. success: function (htmlCallBack) {
  983. //modify html and return
  984. return htmlCallBack;
  985. }
  986. },
  987. iframe: {
  988. class: ''
  989. }
  990. },
  991. language: { //language setting
  992. nav: {
  993. title: 'Tab', //default tab's tittle
  994. dropdown: '<i class="mdi mdi-menu"></i>', //right tools dropdown name
  995. showActivedTab: '显示当前选项卡', //show active tab
  996. closeAllTabs: '关闭所有标签页', //close all tabs
  997. closeOtherTabs: '关闭其他标签页', //close other tabs
  998. }
  999. }
  1000. };
  1001. })(jQuery));