前端开发插件

99 阅读1分钟

案例: 点击 tab 获取对应的 tab-item , 并随之切换 page 中 page-item 的内容和样式

  1. 普通方法
// plugin.js
var tabItem = document.getElementsByClassName('tab-item'),
    pageItem = document.getElementsByClassName('page-item');
    for(var i = 0; i < tabItem.length; i++){
      (function(j){
        console.log(tabItem[j]);
        tabItem[j].onclick = function(){
          for(var k = 0; k < tabItem.length; k++){
            tabItem[k].className = 'tab-item'
            pageItem[k].className = 'page-item'
          }
          this.className += ' cur'
          pageItem[j].className += ' active'
        }
      })(i)
    }
  1. 插件方法
// plugin.js
;(function(){
  var Tab = function(opt){
    this.tabs = document.getElementsByClassName(opt.tabItem)
    this.pages = document.getElementsByClassName(opt.pageItem)
    this.bindClick(opt.tabItem, opt.pageItem, opt.cur, opt.active)
  }

  Tab.prototype = {
    bindClick: function(tabItem, pageItem, cur, active){
      var tabs = this.tabs
      var pages = this.pages
      for(var i = 0; i < tabs.length; i++){
        (function(j){
          tabs[j].onclick = function(){
            for(var k = 0; k < tabs.length; k++){
              tabs[k].className = tabItem;
              pages[k].className = pageItem
            }
            this.className = tabItem + ' ' + cur
            pages[j].className = pageItem + ' ' + active
          }
        })(i)
      }
    }
  }
  window.Tab = Tab;
})();
  1. 引用插件
// index.html
 <script src="./plugin.js"></script>
  <script type="text/javascript">
    var tab = new Tab({
      tabItem: 'tab-item',
      pageItem: 'page-item',
      cur: 'cur',
      active: 'active',
    })
  </script>