How can I add and remove an active class to an element in pure JavaScript

前端 未结 9 1179
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 20:29

I am trying to make a navigation menu I did all the HTML and CSS when come to javascript I am struck in the middle I am able to add a class to the

9条回答
  •  半阙折子戏
    2020-12-17 20:40

    window.myFunction = function(event) {
      var elms = document.querySelectorAll('ul li a');
      // reset all you menu items
      for (var i = 0, len = elms.length; i < len; i++) {
        elms[i].classList.remove('active');
      }
      // mark as active clicked menu item
      event.target.classList.add("active");
    };
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    header {
      width: 100%;
      height: auto;
      max-width: 600px;
      margin: 0 auto;
    }
    
    nav {
      width: 100%;
      height: 40px;
      background-color: cornflowerblue;
    }
    
    ul {
      list-style-type: none;
    }
    
    li {
      display: inline-block;
    }
    
    a {
      text-decoration: none;
      padding: 8px 15px;
      display: block;
      text-transform: capitalize;
      background-color: pink;
      color: #fff;
    }
    
    a.active {
      background-color: blue;
    }
    
    .active {
      ackground-color: red;
    }

提交回复
热议问题