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

前端 未结 9 1181
被撕碎了的回忆
被撕碎了的回忆 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:52

    HTML

    
    

    CSS

        * {
          margin: 0;
          padding: 0;
          box-sizing: border-box;
        }
    
        *::before, *::after {
            box-sizing: border-box;
        }
    
        .container {
          width: 100%;
          max-width: 1024px;
          display: block;
          margin: 30px auto;
        }
    
        ul {
          list-style: none;
        }
    
        a {
          text-decoration: none;
        }
    
        .nav {
          display: flex;
          flex-direction: row;
          justify-content: space-around;
          align-items: center;
        }
    
        .nav__item {
          padding: 1rem;
        }
    
        .nav__link {
          display: block;
          padding: .3125rem 1.5rem;
          text-transform: uppercase;
        }
    
        .nav__link.active  {
          border: 1px solid #ff4b4c;
          color: #ff4b4c;
        }
    

    JS

        document.addEventListener('DOMContentLoaded', function() {
    
          const selector = '.nav__link';
          const elems = Array.from(document.querySelectorAll(selector));
          const navigation = document.querySelector('nav');
    
          function makeActive(evt) {
            const target = evt.target;
    
             if (!target || !target.matches(selector)) {
               return;
             }
    
            elems.forEach(elem => elem.classList.remove('active'));
            evt.target.classList.add('active');
          };
    
          navigation.addEventListener('mousedown', makeActive);
    
        });
    

    BTW: A great solution is here: https://gomakethings.com/getting-all-sibling-elements-when-a-link-or-button-is-clicked-with-vanilla-js/

提交回复
热议问题