One, foreword

Tab-bar effect switch is a common functional requirement, it actually uses the exclusive thought of JS.

So what is exclusivity?

In short, when the listener is set up, all styles are cleared, and then styles are added as required.

2. Case analysis

1. Requirements analysis

Mouse over li, li itself changes color (add class), and the corresponding span is displayed (add class);

2. Function realization

1. Light the box. 2. Display boxes with index values.

Steps:

  • 1. Obtain the event source and related elements
  • 2. Bind events
  • 3. Write event drivers (exclusivity)

HTML:

<div id="box" class="active">
    <ul>
        <li>shoes</li>
        <li>socks</li>
        <li>hat</li>
        <li>The trousers</li>
        <li>The skirt</li>
    </ul>
<div class="clearfix"></div>
<span class="show">shoes</span>
<span>socks</span>
<span>hat</span>
<span>The trousers</span>
<span>The skirt</span>
</div>
Copy the code

CSS:

* {
    margin: 0;
    padding: 0;
}
li {
    list-style: none;
}
.clearfix {
    clear: both;
}
#box {
    width: 450px;
    height: 500px;
    background-color: # 333;
    margin: 100px auto;
    border: 1px solid #ccc;
    text-align: center;
}
#box ul {
    width: 450px;
    height: 50px;
    text-align: center;
}
#box ul li {
    width: 60px;
    float: left;
    color: #eee;
    background-color: # 333;
    font-size: 25px;
    line-height: 50px;
    padding: 5px 15px;
    cursor: pointer;
}
#box ul li:hover {
    color: # 333;
    background-color: #ccc;
}
#box.active {
    background-color: #ccc;
}
#box span {
    display: none;
    width: 450px;
    height: 440px;
    font-size: 50px;
    line-height: 440px;
}
#box .show {
    display: block;
}
Copy the code

JS:

window.onload = function() {
    //1. Get the event source and related elements
    var liArr = document.getElementsByTagName('li');
    var spanArr = document.getElementsByTagName('span');
    //2. Bind events
    for(var i = 0; i < liArr.length; i++) {
        //3. Write event drivers (exclusive thinking)
        liArr[i].index = i;
        liArr[i].onmouseover = function() {
            for(var j = 0; j < spanArr.length; j++) {
                // Clear all styles
                liArr[j].classList = ' ';
                spanArr[j].classList = ' ';
            }
        // Add the desired styles
        this.classList = 'active';
        spanArr[this.index].className = 'show'; }}}Copy the code

Third, summary

When faced with such a requirement (TAB switching), the first thing to think about is “exclusivity”.

The key is a two-step process. First, when the event is listening, use the for loop to iterate over all the Li and SPAN elements and clear all their styles.

The second step is to jump out of the loop and add styles separately as required.