multitabs.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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. if ($nextLi.length) {
  445. self.active($nextLi);
  446. //} else if ($prevLi.size()) {
  447. } else if ($prevLi.length) {
  448. self.active($prevLi);
  449. }
  450. }
  451. self._delStorage($navTab.attr('data-id')); //remove tab from session storage
  452. $navTabLi.remove();
  453. $tabPane.remove();
  454. return self;
  455. },
  456. /**
  457. * close others tab
  458. * @return self Chain structure.
  459. */
  460. closeOthers: function () {
  461. var self = this,
  462. $el = self.$element;
  463. $el.navPanelList.find('li:not(.active)').find('a:not([data-type="main"])').each(function () {
  464. var $navTab = $(this);
  465. self._delStorage($navTab.attr('data-id')); //remove tab from session storage
  466. self._getTabPane($navTab).remove(); //remove tab-content
  467. $navTab.parent('li').remove(); //remove navtab
  468. });
  469. $el.navPanelList.css("margin-left", "0");
  470. return self;
  471. },
  472. /**
  473. * focus actived tab
  474. * @return self Chain structure.
  475. */
  476. showActive: function () {
  477. var self = this,
  478. $el = self.$element;
  479. var navTab = $el.navPanelList.find('li.active:first a');
  480. self._fixTabPosition(navTab);
  481. return self;
  482. },
  483. /**
  484. * close all tabs, (except main tab)
  485. * @return self Chain structure.
  486. */
  487. closeAll: function () {
  488. var self = this,
  489. $el = self.$element;
  490. $el.navPanelList.find('a:not([data-type="main"])').each(function () {
  491. var $navTab = $(this);
  492. self._delStorage($navTab.attr('data-id')); //remove tab from session storage
  493. self._getTabPane($navTab).remove(); //remove tab-content
  494. $navTab.parent('li').remove(); //remove navtab
  495. });
  496. self.active($el.navPanelList.find('a[data-type="main"]:first').parent('li'));
  497. return self;
  498. },
  499. /**
  500. * init function
  501. * @param options
  502. * @returns self
  503. * @private
  504. */
  505. _init: function (options) {
  506. var self = this,
  507. $el = self.$element;
  508. $el.html(defaultLayoutTemplates[options.nav.layout]
  509. .replace('{mainClass}', options.class)
  510. .replace('{navClass}', options.nav.class)
  511. .replace(/\{nav-tabs\}/g, options.nav.style)
  512. .replace(/\{backgroundColor\}/g, options.nav.backgroundColor)
  513. .replace('{dropdown}', options.language.nav.dropdown)
  514. .replace('{showActivedTab}', options.language.nav.showActivedTab)
  515. .replace('{closeAllTabs}', options.language.nav.closeAllTabs)
  516. .replace('{closeOtherTabs}', options.language.nav.closeOtherTabs)
  517. );
  518. $el.wrapper = $el.find('.mt-wrapper:first');
  519. $el.nav = $el.find('.mt-nav-bar:first');
  520. $el.navToolsLeft = $el.nav.find('.mt-nav-tools-left:first');
  521. $el.navPanel = $el.nav.find('.mt-nav-panel:first');
  522. $el.navPanelList = $el.nav.find('.mt-nav-panel:first ul');
  523. //$el.navTabMain = $('#multitabs_main_0');
  524. $el.navToolsRight = $el.nav.find('.mt-nav-tools-right:first');
  525. $el.tabContent = $el.find('.tab-content:first');
  526. //hide tab-header if maxTabs less than 1
  527. if (options.nav.maxTabs <= 1) {
  528. options.nav.maxTabs = 1;
  529. $el.nav.hide();
  530. }
  531. //set the nav-panel width
  532. var toolWidth = $el.nav.find('.mt-nav-tools-left:visible:first').width() + $el.nav.find('.mt-nav-tools-right:visible:first').width();
  533. $el.navPanel.css('width', 'calc(100% - ' + toolWidth + 'px)');
  534. self.options = options;
  535. return self;
  536. },
  537. /**
  538. * final funcion for after init Multitabs
  539. * @returns self
  540. * @private
  541. */
  542. _final: function () {
  543. var self = this,
  544. $el = self.$element,
  545. options = self.options,
  546. storage, init = options.init,
  547. param;
  548. if (supportStorage(options.cache)) {
  549. storage = self._storage();
  550. self._resetStorage({});
  551. $.each(storage, function (k, v) {
  552. self.create(v, false);
  553. })
  554. }
  555. if ($.isEmptyObject(storage)) {
  556. init = (!$.isEmptyObject(init) && init instanceof Array) ? init : defaultInit;
  557. for (var i = 0; i < init.length; i++) {
  558. param = self._getParam(init[i]);
  559. if (param) {
  560. self.create(param);
  561. }
  562. }
  563. }
  564. //if no any tab actived, active the main tab
  565. if (!$el.navPanelList.children('li.active').length) {
  566. self.active($el.navPanelList.find('[data-type="main"]:first'));
  567. }
  568. return self;
  569. },
  570. /**
  571. * bind action
  572. * @return self
  573. * @private
  574. */
  575. _listen: function () {
  576. var self = this,
  577. $el = self.$element,
  578. options = self.options;
  579. //create tab
  580. handler($(document), 'click', options.selector, function () {
  581. self.create(this, true);
  582. if (!$(this).parent().parent('ul').hasClass('dropdown-menu')) { // 20190402改,下拉菜单中的网址采用data-url,并且不阻止后面的动作
  583. return false; //Prevent the default selector action
  584. }
  585. });
  586. //active tab
  587. handler($el.nav, 'click', '.mt-nav-tab', function () {
  588. self.active(this);
  589. });
  590. //drag tab
  591. if (options.nav.draggable) {
  592. handler($el.navPanelList, 'mousedown', '.mt-nav-tab', function (event) {
  593. var $navTab = $(this),
  594. $navTabLi = $navTab.closest('li');
  595. var $prevNavTabLi = $navTabLi.prev();
  596. var dragMode = true,
  597. moved = false,
  598. isMain = ($navTab.data('type') === "main");
  599. var tmpId = 'mt_tmp_id_' + new Date().getTime(),
  600. navTabBlankHtml = '<li id="' + tmpId + '" class="mt-dragging" style="width:' + $navTabLi.outerWidth() + 'px; height:' + $navTabLi.outerHeight() + 'px;"><a style="width: 100%; height: 100%; "></a></li>';
  601. var abs_x = event.pageX - $navTabLi.offset().left + $el.nav.offset().left;
  602. $navTabLi.before(navTabBlankHtml);
  603. $navTabLi.addClass('mt-dragging mt-dragging-tab').css({
  604. 'left': event.pageX - abs_x + 'px'
  605. });
  606. $(document).on('mousemove', function (event) {
  607. if (dragMode && !isMain) {
  608. $navTabLi.css({
  609. 'left': event.pageX - abs_x + 'px'
  610. });
  611. $el.navPanelList.children('li:not(".mt-dragging")').each(function () {
  612. var leftWidth = $(this).offset().left + $(this).outerWidth() + 20; //20 px more for gap
  613. if (leftWidth > $navTabLi.offset().left) {
  614. if ($(this).next().attr('id') !== tmpId) {
  615. moved = true;
  616. $prevNavTabLi = $(this);
  617. $('#' + tmpId).remove();
  618. $prevNavTabLi.after(navTabBlankHtml);
  619. }
  620. return false;
  621. }
  622. });
  623. }
  624. }).on("selectstart", function () { //disable text selection
  625. if (dragMode) {
  626. return false;
  627. }
  628. }).on('mouseup', function () {
  629. if (dragMode) {
  630. $navTabLi.removeClass('mt-dragging mt-dragging-tab').css({'left': 'auto'});
  631. if (moved) {
  632. $prevNavTabLi.after($navTabLi);
  633. }
  634. $('#' + tmpId).remove();
  635. }
  636. dragMode = false;
  637. });
  638. });
  639. }
  640. // 右键菜单
  641. handler($el.nav, 'contextmenu', '.mt-nav-tab', function (event) {
  642. event.preventDefault();
  643. var menu = $('<ul class="dropdown-menu" role="menu" id="contextify-menu"/>'),
  644. $this = $(this),
  645. $nav = $this.closest('li'),
  646. $navTab = self._getNavTab($nav);
  647. var menuData = [
  648. {text: '刷新', onclick: function(){
  649. var $tabPane = self._getTabPane($navTab);
  650. $tabPane.attr('src', $tabPane.attr('src'));
  651. menu.hide();
  652. return false;
  653. }}
  654. ];
  655. var param = self._getParam($navTab);
  656. if (param.type !== 'main') {
  657. menuData.push(
  658. {text: '关闭', onclick: function(){
  659. self.close($navTab);
  660. menu.hide();
  661. return false;
  662. }}
  663. );
  664. }
  665. var l = menuData.length, i;
  666. for (i = 0; i < l; i++) {
  667. var item = menuData[i],
  668. el = $('<li/>');
  669. el.append('<a/>');
  670. var a = el.find('a');
  671. a.on('click', item.onclick);
  672. a.css('cursor', 'pointer');
  673. a.html(item.text);
  674. menu.append(el);
  675. }
  676. var currentMenu = $("#contextify-menu");
  677. if (currentMenu.length > 0) {
  678. if(currentMenu !== menu) {
  679. currentMenu.replaceWith(menu);
  680. }
  681. } else {
  682. $('body').append(menu);
  683. }
  684. var clientTop = $(window).scrollTop() + event.clientY,
  685. x = (menu.width() + event.clientX < $(window).width()) ? event.clientX : event.clientX - menu.width(),
  686. y = (menu.height() + event.clientY < $(window).height()) ? clientTop : clientTop - menu.height();
  687. menu.css('top', y).css('left', x).css('position', 'fixed').show();
  688. $(this).parents().on('mouseup', function () {
  689. menu.hide();
  690. });
  691. $('#iframe-content').find('iframe').contents().find('body').on('mouseup', function () {
  692. menu.hide();
  693. });
  694. });
  695. //close tab
  696. handler($el.nav, 'click', '.mt-close-tab', function () {
  697. self.close($(this).closest('li'));
  698. return false; //Avoid possible BUG
  699. });
  700. //move left
  701. handler($el.nav, 'click', '.mt-move-left', function () {
  702. self.moveLeft();
  703. return false; //Avoid possible BUG
  704. });
  705. //move right
  706. handler($el.nav, 'click', '.mt-move-right', function () {
  707. self.moveRight();
  708. return false; //Avoid possible BUG
  709. });
  710. //show actived tab
  711. handler($el.nav, 'click', '.mt-show-actived-tab', function () {
  712. self.showActive();
  713. //return false; //Avoid possible BUG
  714. });
  715. //close all tabs
  716. handler($el.nav, 'click', '.mt-close-all-tabs', function () {
  717. self.closeAll();
  718. //return false; //Avoid possible BUG
  719. });
  720. //close other tabs
  721. handler($el.nav, 'click', '.mt-close-other-tabs', function () {
  722. self.closeOthers();
  723. //return false; //Avoid possible BUG
  724. });
  725. //fixed the nav-bar
  726. var navHeight = $el.nav.outerHeight();
  727. $el.tabContent.css('paddingTop', navHeight);
  728. if (options.nav.fixed) {
  729. handler($(window), 'scroll', function () {
  730. var scrollTop = $(this).scrollTop();
  731. scrollTop = scrollTop < ($el.wrapper.height() - navHeight) ? scrollTop + 'px' : 'auto';
  732. $el.nav.css('top', scrollTop);
  733. return false; //Avoid possible BUG
  734. });
  735. }
  736. //if layout === 'classic' show hide list in dropdown menu
  737. if (options.nav.layout === 'classic') {
  738. handler($el.nav, 'click', '.mt-dropdown:not(.open)', function () { //just trigger when dropdown not open.
  739. var list = self._getHiddenList();
  740. var $dropDown = $el.navToolsRight.find('.mt-hidden-list:first').empty();
  741. if (list) { //when list is not empty
  742. while (list.prevList.length) {
  743. $dropDown.append(list.prevList.shift().clone());
  744. }
  745. while (list.nextList.length) {
  746. $dropDown.append(list.nextList.shift().clone());
  747. }
  748. } else {
  749. $dropDown.append('<li>empty</li>');
  750. }
  751. // return false; //Avoid possible BUG
  752. });
  753. }
  754. return self;
  755. },
  756. /**
  757. * get the multitabs object's param
  758. * @param obj multitabs's object
  759. * @returns param param
  760. * @private
  761. */
  762. _getParam: function (obj) {
  763. if ($.isEmptyObject(obj)) {
  764. return false;
  765. }
  766. var self = this,
  767. options = self.options,
  768. param = {},
  769. $obj = $(obj),
  770. data = $obj.data();
  771. //content
  772. param.content = data.content || obj.content || '';
  773. if (!param.content.length) {
  774. //url
  775. param.url = data.url || obj.url || $obj.attr('href') || $obj.attr('url') || '';
  776. param.url = $.trim(decodeURIComponent(param.url.replace('#', '')));
  777. } else {
  778. param.url = '';
  779. }
  780. if (!param.url.length && !param.content.length) {
  781. return false;
  782. }
  783. //refresh
  784. param.refresh = data.hasOwnProperty('refresh') || obj.hasOwnProperty('refresh') || options.refresh;
  785. //iframe
  786. param.iframe = data.iframe || obj.iframe || isExtUrl(param.url) || options.iframe;
  787. //type
  788. param.type = data.type || obj.type || options.type;
  789. //title
  790. param.title = data.title || obj.title || $obj.text() || param.url.replace('http://', '').replace('https://', '') || options.language.nav.title;
  791. param.title = trimText(param.title, options.nav.maxTitleLength);
  792. //active
  793. param.active = data.active || obj.active || false;
  794. //index
  795. param.index = data.index || obj.index || getTabIndex(param.type, options.nav.maxTabs);
  796. //id
  797. param.did = data.did || obj.did || this._generateId(param);
  798. return param;
  799. },
  800. /**
  801. * session storage for tab list
  802. * @param key
  803. * @param param
  804. * @returns storage
  805. * @private
  806. */
  807. _storage: function (key, param) {
  808. if (supportStorage(this.options.cache)) {
  809. var storage = JSON.parse(sessionStorage.multitabs || '{}');
  810. if (!key) {
  811. return storage;
  812. }
  813. if (!param) {
  814. return storage[key];
  815. }
  816. storage[key] = param;
  817. sessionStorage.multitabs = JSON.stringify(storage);
  818. return storage;
  819. }
  820. return {};
  821. },
  822. /**
  823. * delete storage by key
  824. * @param key
  825. * @private
  826. */
  827. _delStorage: function (key) {
  828. if (supportStorage(this.options.cache)) {
  829. var storage = JSON.parse(sessionStorage.multitabs || '{}');
  830. if (!key) {
  831. return storage;
  832. }
  833. delete storage[key];
  834. sessionStorage.multitabs = JSON.stringify(storage);
  835. return storage;
  836. }
  837. return {};
  838. },
  839. /**
  840. * reset storage
  841. * @param storage
  842. * @private
  843. */
  844. _resetStorage: function (storage) {
  845. if (supportStorage(this.options.cache) && typeof storage === "object") {
  846. sessionStorage.multitabs = JSON.stringify(storage);
  847. }
  848. },
  849. /**
  850. * check if exist multitabs obj
  851. * @param param
  852. * @private
  853. */
  854. _exist: function (param) {
  855. if (!param || !param.url) {
  856. return false;
  857. }
  858. var self = this,
  859. $el = self.$element;
  860. var $navTab = $el.navPanelList.find('a[data-url="' + param.url + '"]:first');
  861. if ($navTab.length) {
  862. return $navTab;
  863. } else {
  864. return false;
  865. }
  866. },
  867. /**
  868. * get tab-pane from tab
  869. * @param tab
  870. * @returns {*}
  871. * @private
  872. */
  873. _getTabPane: function (navTab) {
  874. return $('#' + $(navTab).attr('data-id'));
  875. },
  876. /**
  877. * get real navTab in the panel list.
  878. * @param navTab
  879. * @returns navTab
  880. * @private
  881. */
  882. _getNavTab: function (navTab) {
  883. var self = this,
  884. $el = self.$element;
  885. var dataId = $(navTab).attr('data-id') || $(navTab).find('a').attr('data-id');
  886. return $el.navPanelList.find('a[data-id="' + dataId + '"]:first');
  887. },
  888. /**
  889. * fix nav navTab position
  890. * @param navTab
  891. * @private
  892. */
  893. _fixTabPosition: function (navTab) {
  894. var self = this,
  895. $el = self.$element,
  896. $navTabLi = $(navTab).parent('li'),
  897. tabWidth = $navTabLi.outerWidth(true),
  898. prevWidth = $navTabLi.prev().outerWidth(true),
  899. pprevWidth = $navTabLi.prev().prev().outerWidth(true),
  900. sumPrevWidth = sumDomWidth($navTabLi.prevAll()),
  901. sumNextWidth = sumDomWidth($navTabLi.nextAll()),
  902. navPanelWidth = $el.navPanel.outerWidth(true),
  903. sumTabsWidth = sumDomWidth($el.navPanelList.children('li')),
  904. leftWidth = 0;
  905. //all nav navTab's width no more than nav-panel's width
  906. if (sumTabsWidth < navPanelWidth) {
  907. leftWidth = 0
  908. } else {
  909. //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
  910. if ((prevWidth + tabWidth + sumNextWidth) <= navPanelWidth) {
  911. leftWidth = sumPrevWidth; //sum width of left part
  912. //add width from the left, calcular the maximum tabs can contained by nav-panel
  913. while ((sumTabsWidth - leftWidth + prevWidth) < navPanelWidth) {
  914. $navTabLi = $navTabLi.prev(); //change the left navTab
  915. leftWidth -= $navTabLi.outerWidth(); //reduce the left part width
  916. }
  917. } else { //nav-panel can not contain the navTab and his right tabs
  918. //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.
  919. if ((sumPrevWidth + tabWidth) > navPanelWidth) {
  920. leftWidth = sumPrevWidth - prevWidth - pprevWidth
  921. }
  922. }
  923. }
  924. leftWidth = leftWidth > 0 ? leftWidth : 0; //avoid leftWidth < 0 BUG
  925. $el.navPanelList.animate({
  926. marginLeft: 0 - leftWidth + "px"
  927. }, "fast");
  928. },
  929. /**
  930. * hidden tab list
  931. * @returns hidden tab list, the prevList and nextList
  932. * @private
  933. */
  934. _getHiddenList: function () {
  935. var self = this,
  936. $el = self.$element,
  937. navPanelListMarginLeft = Math.abs(parseInt($el.navPanelList.css("margin-left"))),
  938. navPanelWidth = $el.navPanel.outerWidth(true),
  939. sumTabsWidth = sumDomWidth($el.navPanelList.children('li')),
  940. tabPrevList = [],
  941. tabNextList = [],
  942. $navTabLi, marginLeft;
  943. //all tab's width no more than nav-panel's width
  944. if (sumTabsWidth < navPanelWidth) {
  945. return false;
  946. } else {
  947. $navTabLi = $el.navPanelList.children('li:first');
  948. //overflow hidden left part
  949. marginLeft = 0;
  950. //from the first tab, add all left part hidden tabs
  951. while ((marginLeft + $navTabLi.width()) <= navPanelListMarginLeft) {
  952. marginLeft += $navTabLi.outerWidth(true);
  953. tabPrevList.push($navTabLi);
  954. $navTabLi = $navTabLi.next();
  955. }
  956. //overflow hidden right part
  957. if (sumTabsWidth > marginLeft) { //check if the right part have hidden tabs
  958. $navTabLi = $el.navPanelList.children('li:last');
  959. marginLeft = sumTabsWidth; //set margin-left as the Rightmost, and reduce one and one.
  960. while (marginLeft > (navPanelListMarginLeft + navPanelWidth)) {
  961. marginLeft -= $navTabLi.outerWidth(true);
  962. tabNextList.unshift($navTabLi); //add param from top
  963. $navTabLi = $navTabLi.prev();
  964. }
  965. }
  966. return {
  967. prevList: tabPrevList,
  968. nextList: tabNextList
  969. };
  970. }
  971. },
  972. /**
  973. * check if tab-pane is iframe, and add/remove class
  974. * @param tabPane
  975. * @private
  976. */
  977. _fixTabContentLayout: function (tabPane) {
  978. var $tabPane = $(tabPane);
  979. if ($tabPane.is('iframe')) {
  980. $('body').addClass('full-height-layout');
  981. /** fix chrome croll disappear bug **/
  982. $tabPane.css("height", "99%");
  983. window.setTimeout(function () {
  984. $tabPane.css("height", "100%");
  985. }, 0);
  986. } else {
  987. $('body').removeClass('full-height-layout');
  988. }
  989. },
  990. };
  991. /**
  992. * Entry function
  993. * @param option
  994. */
  995. $.fn.multitabs = function (option, id) {
  996. var self = $(this),
  997. did = id ? id : 'multitabs',
  998. multitabs = $(document).data(did),
  999. options = typeof option === 'object' && option,
  1000. opts;
  1001. if (!multitabs) {
  1002. opts = $.extend(true, {}, $.fn.multitabs.defaults, options, self.data());
  1003. opts.nav.style = (opts.nav.style === 'nav-pills') ? 'nav-pills' : 'nav-tabs';
  1004. multitabs = new MultiTabs(this, opts);
  1005. $(document).data(did, multitabs);
  1006. }
  1007. return $(document).data(did);
  1008. };
  1009. /**
  1010. * Default Options
  1011. * @type {}
  1012. */
  1013. $.fn.multitabs.defaults = {
  1014. selector: '.multitabs', //selector text to trigger multitabs.
  1015. iframe: false, //Global iframe mode, default is false, is the auto mode (for the self page, use ajax, and the external, use iframe)
  1016. cache: false,
  1017. class: '', //class for whole multitabs
  1018. type: 'info', //change the info content name, is not necessary to change.
  1019. init: [],
  1020. refresh: false,
  1021. nav: {
  1022. backgroundColor: '#f5f5f5', //default nav-bar background color
  1023. class: '', //class of nav
  1024. draggable: true, //nav tab draggable option
  1025. fixed: false, //fixed the nav-bar
  1026. layout: 'default', //it can be 'default', 'classic' (all hidden tab in dropdown list), and simple
  1027. maxTabs: 15, //Max tabs number (without counting main tab), when is 1, hide the whole nav
  1028. maxTitleLength: 25, //Max title length of tab
  1029. showCloseOnHover: true, //while is true, show close button in hover, if false, show close button always
  1030. style: 'nav-tabs' //can be nav-tabs or nav-pills
  1031. },
  1032. content: {
  1033. ajax: {
  1034. class: '', //Class for ajax tab-pane
  1035. error: function (htmlCallBack) {
  1036. //modify html and return
  1037. return htmlCallBack;
  1038. },
  1039. success: function (htmlCallBack) {
  1040. //modify html and return
  1041. return htmlCallBack;
  1042. }
  1043. },
  1044. iframe: {
  1045. class: ''
  1046. }
  1047. },
  1048. language: { //language setting
  1049. nav: {
  1050. title: 'Tab', //default tab's tittle
  1051. dropdown: '<i class="mdi mdi-menu"></i>', //right tools dropdown name
  1052. showActivedTab: '显示当前选项卡', //show active tab
  1053. closeAllTabs: '关闭所有标签页', //close all tabs
  1054. closeOtherTabs: '关闭其他标签页', //close other tabs
  1055. }
  1056. }
  1057. };
  1058. })(jQuery));