A simple tab JS plug-in

Time:2022-1-2

It is estimated that there are no such articles on the front end in about two or three months. First, I feel that I am too delicious. Second, I am also lazy and confused, but I have no results. Today, because I was chatting with some students, I suddenly felt very depressed. I had a feeling that I couldn’t see where the future was, so I forced myself to learn and see how to write the JS plug-in. Today, I write a simple tab plug-in. I also read other people’s blogs to learn and implement it, and then add some of my own understanding.

I Realization effect


Although it is a little crude, you can see that the tab we wrote is introduced into the HTML file JS plug-in, to achieve tab switching, you only need one line of code.

II tab. JS structure

Let’s take a look at the structure as a whole

//At first, of course, you create a constructor tab
function Tab(){
  //There is only one line of code, which is to call its own initialization method
  this.init.apply(this,arguments);
}

//All the required properties and methods are written in the prototype
Tab.prototype = {
  //Attributes
  //some code
  //Method
  //some code
}

III Implementation of some methods

  1. We do not use closures here and execute them immediately, so we need an initialization function to initialize all attributes. In init:

init:function(ela,elb,paramObj){
  //Generally, there will be a configuration object in the plug-in with default values
  this.defaultOptions = {
    curClass:'current',
    type:'mouseover',
    delay:150
  }
  //Then we will check whether the user has passed in the configuration parameters. If so, we will use the user's configuration. Here, we use an extend method
  this.options = this.extend(this.defaultOptions, paramObj || {})
}

Extend is actually an object expansion method, which covers the attributes of object B to object A. This method is written directly in JQ, but not in JS. We need to simulate it ourselves. We write this method outside init

extend:function(a,b){
  for(var i in b){
    //This is to detect whether the attribute detected by the for loop is B itself
    if(b.hasOwnProperty(i)){
      a[i] = b[i]
    }
  }
  return a;
}

In init, there are some basic attributes, such as obtaining the dom of the navigation bar, the dom of the content block, their sub elements and the number of sub elements, which will be used in later traversal. For details, see the source code attached to the article. Finally, we need to bind each navigation event in init, one is trigger and the other is cancel. Canceling is onmouseout naturally. If it is triggered, you can pass in parameters to make it. Using brackets can solve this problem

for(var i=0;i<this.tLen;i++){
    this.triggerItem[i]['on' + this.options.type] = this.change(i)
    this.triggerItem[i].onmouseout = function(){
      clearTime(self.timer);
      self.timer = null;
    }
}
  1. Methods for adding and eliminating class names
    Generally, the methods used to achieve this switching effect are the addition and elimination of class names, so the operation methods of class names are very important

addClass:function(el,name){
  var arr = [],
       str = el.className,
       arr = str.split(/\s+/),
       len = arr.length,
       name = this.trim(name),
  for(var i=0;i<len;i++){
    if(arr[i] === name){
      //Direct return already exists
      return;
    }
   }
  el.className += ' ' + name;
  el = null; 
}

The method of eliminating class names is similar, mainly using a splice method.

  1. Change tab toggle function
    This is the function bound to each navigation bar

A closure is also used here, which returns a new function each time

change:function(index){
  var self = this;
  return function(){
    self.timer = setTimeout(function(){
        for(var i=0;i<self.tLen;i++){
          if(i == index){
            self.addClass(self.triggerItem[index],self.options.curClass);
            self.listItem[i].style.display = 'block';
          }else{
            self.removeClass(self.triggerItem[i],self.options.curClass);
            self.listItem[i].style.display = 'none';
          }
        }
      },self.options.delay)
  }
}

IV summary

In fact, this is a very simple package. Those who just started learning the front end must have done this switching effect, and this package uses the inheritance of the object prototype chain to achieve the reuse of some methods. Main knowledge points:
1. Init initialization is required for each new object
2. Write the required attributes and methods in prototype
3. Use closures to bind events to dom
4. Pay attention to the details of class name processing, such as checking whether it already exists, whether there are spaces, etc
5. Some events shall be delayed, and the site shall be cleaned after the event is completed

V Two more words at the end

This article actually has no valuable content, but I hope it is a learning start for me, just like when I first started learning the front end, the pure desire for technology. I’m going to graduate in a few months before I realize that my university has really passed. Just like when you were a freshman or sophomore, when you went home and had a high school reunion, you realized that high school was really over. Even if that person stood in front of you, you felt different from him. But there’s no way. This is growth. At that time, I thought that if I could come back, I must study hard and catch up with my deskmate. Now the university is going to pass. Of course, there are regrets, but there will be no idea of starting over again, because even if you start over again, it must be the same. What really matters is the change of your mind. If you don’t come back again, you can still study well, and if you don’t come back again, you can still pursue the people you like. Why limit yourself to an environment and an identity. Although I have been stimulated a lot and feel a little depressed during this period, I still have to work hard and live a good life. Just like before, I always thought that no one would read my articles. As a result, occasionally someone will praise you and reply to you. Maybe it’s just a few words, but it’s really a great encouragement for me. I hope I can grow and become stronger in the New Year!

Source address:https://coding.net/u/ly550275…