如何在纯JavaScript中为元素添加和删除活动类

时间:2016-08-17 07:06:11

标签: javascript html css

我正在尝试制作导航菜单,当我来到 javascript 时,我做了所有 HTML CSS 我在中间被击中我能够为元素添加一个类,但我无法删除类剩余的元素。请帮帮我 这是我的代码

<!DOCTYPE html>
    <html>
    <head>
        <title>Navigation class Toggling</title>

        <style type="text/css">
        * {
            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: darkgray;
            color: #fff;
        }
        a.active {
            background-color: cornflowerblue;
        }
        </style>
    </head>
    <body>
    <header>
        <nav>
            <ul onclick="myFunction(event)">
                <li><a href="#">home</a></li>
                <li><a href="#">about</a></li>
                <li><a href="#">service</a></li>
                <li><a href="#">profile</a></li>
                <li><a href="#">portfolio</a></li>
                <li><a href="#">contact</a></li>
            </ul>
        </nav>
    </header>
    <script type="text/javascript">
        function myFunction(e) {
            e.target.className = "active";
        }
    </script>
    </body>
    </html>

这是我的Codepen

9 个答案:

答案 0 :(得分:17)

使用document.querySelectorAll查找当前具有active类的元素,然后您可以删除该类。

function myFunction(e) {
  var elems = document.querySelectorAll(".active");
  [].forEach.call(elems, function(el) {
    el.classList.remove("active");
  });
  e.target.className = "active";
}

JSFIDDLE

您也可以使用document.querySelectorAll

代替document.querySelector
 function myFunction(e) {
  var elems = document.querySelector(".active");
  if(elems !==null){
   elems.classList.remove("active");
  }
 e.target.className = "active";
}

JSFIDDLE 2

修改

您可以使用document.queryselector选择具有类active的元素,而不是遍历整个集合。同时为ul提供id,以便您可以定位特定元素

function myFunction(e) {
  if (document.querySelector('#navList a.active') !== null) {
    document.querySelector('#navList a.active').classList.remove('active');
  }
  e.target.className = "active";
}
<style type="text/css">* {
  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: darkgray;
  color: #fff;
}

a.active {
  background-color: cornflowerblue;
}
<title>Navigation class Toggling</title>

<header>
  <nav>
    <ul onclick="myFunction(event)" id='navList'>
      <li><a href="#">home</a></li>
      <li><a href="#">about</a></li>
      <li><a href="#">service</a></li>
      <li><a href="#">profile</a></li>
      <li><a href="#">portfolio</a></li>
      <li><a href="#">contact</a></li>
    </ul>
  </nav>
</header>

答案 1 :(得分:3)

您可以使用add方法removetoggle// assuming there's only one with such class name // otherwise you need querySelectorAll and a loop document.querySelector('.active').classList.remove('active')

首先删除上一个的类名:

e.target.classList.add('active')

然后将其添加到新元素:

writelines

答案 2 :(得分:1)

您可以使用“纯”JavaScript Element.classList在DOM元素中添加和删除类。

add:添加指定的类值。如果这些类已存在于元素的属性中,则忽略它们。

remove:删除指定的类值。

使用Document.querySelectorAll()返回文档中与指定的CSS选择器组匹配的元素。

更多信息:

https://developer.mozilla.org/en/docs/Web/API/Element/classList

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

关于您的代码,当用户使用以下代码单击它时,您可以将元素标记为活动元素:

window.myFunction = function(event) {
  // reset all menu items
  document.querySelectorAll('ul li a.active').forEach(function(item) {
  item.classList.remove('active');
})
  // mark as active selected 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: darkgray;
  color: #fff;
}

a.active {
  background-color: cornflowerblue;
}

.active {
  ackground-color: red;
}
<header>
  <nav>
    <ul onclick="window.myFunction(event)">
      <li><a href="#">home</a></li>
      <li><a href="#">about</a></li>
      <li><a href="#">service</a></li>
      <li><a href="#">profile</a></li>
      <li><a href="#">portfolio</a></li>
      <li><a href="#">contact</a></li>
    </ul>
  </nav>
</header>

答案 3 :(得分:1)

HTML

<div class="container">
 <nav>
  <ul class="nav">
    <li class="nav__item"><a class="nav__link active" href="#">Home</a></li>
    <li class="nav__item"><a class="nav__link" href="#">Item 1</a></li>
    <li class="nav__item"><a class="nav__link" href="#">Item 2</a></li>
    <li class="nav__item"><a class="nav__link" href="#">Item 3</a></li>
    <li class="nav__item"><a class="nav__link" href="#">Item 4</a></li>
    <li class="nav__item"><a class="nav__link" href="#">Item 5</a></li>
  </ul>
 </nav>
</div>

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);

    });

顺便说一句:这里有一个很好的解决方案:https://gomakethings.com/getting-all-sibling-elements-when-a-link-or-button-is-clicked-with-vanilla-js/

答案 4 :(得分:0)

你可以在纯粹的javascript中做到这一点

   function myFunction(e,ev) {
      for(var i=0;i<e.children.length;i++)
        {
         e.children[i].childNodes[0].className = "";
          
        }
        ev.target.className = "active"; 
         
        }
<!DOCTYPE html>
    <html>
    <head>
        <title>Navigation class Toggling</title>

        <style type="text/css">
        * {
            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: darkgray;
            color: #fff;
        }
        a.active {
            background-color: cornflowerblue;
        }
        </style>
    </head>
    <body>
    <header>
        <nav>
            <ul onclick="myFunction(this,event)">
                <li><a href="#">home</a></li>
                <li><a href="#">about</a></li>
                <li><a href="#">service</a></li>
                <li><a href="#">profile</a></li>
                <li><a href="#">portfolio</a></li>
                <li><a href="#">contact</a></li>
            </ul>
        </nav>
    </header>
    <script type="text/javascript">
     
    </script>
    </body>
    </html>

答案 5 :(得分:0)

我个人坚持使用document.querySelector方法。 querySelector接受类似CSS的查询,我们将使用它来查找页面上的活动类。如果它存在(if语句),则将其删除并在目标上应用新类。

请注意,使用className = ""会导致所有课程被删除。将classList用于所有事情会更加巧妙。

function myFunction(e) {
    var el = document.querySelector('.active');
  
    // Check if the element exists to avoid a null syntax error on the removal
    if(el) {
      el.classList.remove('active');
    }
		
    e.target.classList.add('active');
}

答案 6 :(得分:0)

<强> JS

var targets = document.querySelectorAll('.some-class');

targets.onclick = function(evt) {
    evt.classList.toggle('{your-class}');
};

为了获得更好的浏览器支持:

targets.onclick = function(evt) {
    var el = evt.target;
    var classes = el.className.split(" ");
    var classIndex = classes.indexOf('{your-class}');

    if (classIndex >= 0) {
        classes.splice(1, classIndex);
    } else {
        classes.push('{your-clas}');
    }

    el.className = classes.join(" ");
});

答案 7 :(得分:0)

&#13;
&#13;
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");
};
&#13;
* {
  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;
}
&#13;
<header>
  <nav>
    <ul onclick="window.myFunction(event)">
      <li><a href="#">home</a></li>
      <li><a href="#">about</a></li>
      <li><a href="#">service</a></li>
      <li><a href="#">profile</a></li>
      <li><a href="#">portfolio</a></li>
      <li><a href="#">contact</a></li>
    </ul>
  </nav>
</header>
&#13;
&#13;
&#13;

答案 8 :(得分:-1)

下面应该有帮助。

//Remove all classes by ID
document.getElementById("elementIdHere").className = "";
//If you wish to keep some classes on the element, use below
document.getElementById("elementIdHere").className = "keepClass";