// tab切换组件 (function(win, $) { var defaultsettings = { // 默认选中的tab项,从0计数 activeindex: 0, // 容器dom对象 dom: null, // 触发tab切换的事件:click|mouseover triggerevent: 'mouseover', // 高亮时的样式名 activecls: '' }; win.tabview = function(opts) { this.cfg = $.extend({}, defaultsettings, opts); this._initview(); this._initevent(); }; $.extend(tabview.prototype, { _initview: function() { var c = this.cfg; var $widget = $(c.dom), $widgethd = $widget.find('> [data-role="head"]'), $widgetbd = $widget.find('> [data-role="body"]'), $tabs = $widgethd.find('[data-role="tab"]'), $tabcons = $widgetbd.find('> [data-role="tab-content"]'); $.extend(this, { $widgethd: $widgethd, $tabs: $tabs, $tabcons: $tabcons }); this.activetabbyindex(c.activeindex); }, _initevent: function() { var c = this.cfg, triggerevent = c.triggerevent, $widgethd = this.$widgethd, self = this; // 用于mouseover触发时的延时 var overtimer = 0; if (triggerevent == 'click') { $widgethd.on('click', '[data-role="tab"]', function(event) { event.preventdefault(); $.proxy(self._activetab, self, $(this))(); }); } else if (triggerevent == 'mouseover') { $widgethd.on('mouseover', '[data-role="tab"]', function() { overtimer && cleartimeout(overtimer); overtimer = settimeout($.proxy(self._activetab, self, $(this)), 500); }).on('mouseout', '[data-role="tab"]', function() { overtimer && cleartimeout(overtimer); }); } }, _activetab: function($tab) { var c = this.cfg, activecls = c.activecls; var $tabs = this.$tabs; var targetid = $tab.data('target'); $tabs.removeclass(activecls); $tab.addclass(activecls); this._activetabcontent(targetid); }, // 通过index激活对应tab activetabbyindex: function(index) { var c = this.cfg, activecls = c.activecls; var $tabs = this.$tabs, $activetab = null, targetid = ''; // 若index合法 if (index >= 0 && index < $tabs.length) { $activetab = $tabs.removeclass(activecls).eq(index).addclass(activecls); targetid = $activetab.data('target'); this._activetabcontent(targetid); } }, _activetabcontent: function(targetid) { var $tabcons = this.$tabcons; $tabcons.addclass('hidden') .filter('[data-id="' + targetid + '"]') .removeclass('hidden'); } }); }(this, jquery));