• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • removeClass()

    移除集合中每个匹配元素上一个,多个或全部样式。

    • .removeClass([className ])
      • className类型: String。每个匹配元素移除的一个或多个用空格隔开的样式名。
    • .removeClass(function(index, class))
      • function(index, class)类型:Function()。一个函数,返回一个或多个将要被移除的样式名。index 参数表示在所有匹配元素的集合中当前元素的索引位置。class 参数表示原有的样式名。

    如果一个样式类名作为一个参数,只有这样式类会被从匹配的元素集合中删除。如果没有样式名作为参数,那么所有的样式类将被移除。

    从所有匹配的每个元素中同时移除多个用空格隔开的样式类,像这样:

    $('p').removeClass('myClass yourClass')
    

    这个方法通常和.addClass()一起使用用来切换元素的样式,像这样:

    $('p').removeClass('myClass noClass').addClass('yourClass');
    

    这里从所有段落删除myClassnoClass样式类,然后yourClass样式被添加。

    用其他样式类替换现有的样式类,我们可以使是有.attr('class','newClass')替换.

    从 jQuery 1.4开始,.removeClass()方法允许我们指定一个函数作为参数,返回将要被删除的样式。

    $('li:last').removeClass(function() {
      return $(this).prev().attr('class');
    });
    

    上例中,移除了最后一个<li>的样式,该样式是倒数第二个<li>的样式。

    例子

    从匹配的元素中移除“blue”样式类。

    <!DOCTYPE html>
    <html>
    <head>
      <style>
     
      p { margin: 4px; font-size:16px; font-weight:bolder; }
      .blue { color:blue; }
      .under { text-decoration:underline; }
      .highlight { background:yellow; }
      </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
      <p class="blue under">Hello</p>
      <p class="blue under highlight">and</p>
      <p class="blue under">then</p>
     
      <p class="blue under">Goodbye</p>
    <script>$("p:even").removeClass("blue");</script>
     
    </body>
    </html>
    

    从匹配的元素中移除“blue”和“under”样式类。

    <!DOCTYPE html>
    <html>
    <head>
      <style>
      p { margin: 4px; font-size:16px; font-weight:bolder; }
      .blue { color:blue; }
      .under { text-decoration:underline; }
      .highlight { background:yellow; }
      </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
      <p class="blue under">Hello</p>
     
      <p class="blue under highlight">and</p>
      <p class="blue under">then</p>
      <p class="blue under">Goodbye</p>
    <script>$("p:odd").removeClass("blue under");</script>
     
    </body>
    </html>
    

    从匹配的元素中移除所有样式类。

    <!DOCTYPE html>
    <html>
    <head>
      <style>
     
      p { margin: 4px; font-size:16px; font-weight:bolder; }
      .blue { color:blue; }
      .under { text-decoration:underline; }
      .highlight { background:yellow; }
      </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
      <p class="blue under">Hello</p>
      <p class="blue under highlight">and</p>
      <p class="blue under">then</p>
     
      <p class="blue under">Goodbye</p>
    <script>$("p:eq(1)").removeClass();</script>
     
    </body>
    </html>
    

    上篇:addClass()

    下篇:toggleClass()