multitabs.js 48 KB

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