removeClass()的作用是从被选元素中移除一个或多个类,最简单的形式是$(selector).removeClass('class1 class2'),或者不带参数直接移除所有类。
动态生成的类名或者根据条件判断是否移除某个类的情况。比如,使用函数作为参数,返回要移除的类名。
一、移除单个类
<!DOCTYPE html><html><head><style>.highlight {background-color: yellow;}</style><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><p class="highlight">这是一个段落。</p><button>移除 highlight 类</button><script>$(document).ready(function() {$("button").click(function() {$("p").removeClass("highlight"); // 移除指定类});});</script></body></html>
效果:点击按钮后,段落的 highlight 类被移除,背景颜色消失。
二、移除多个类
<!DOCTYPE html><html><head><style>.text-red {color: red;}.bold {font-weight: bold;}</style><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><p class="text-red bold">这是一个段落。</p><button>移除 text-red 和 bold 类</button><script>$(document).ready(function() {$("button").click(function() {$("p").removeClass("text-red bold"); // 移除多个类(用空格分隔)});});</script></body></html>
效果:点击按钮后,段落的 text-red 和 bold 类被同时移除。
三、根据条件动态移除类
<!DOCTYPE html><html><head><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><div id="box" class="square red">这是一个盒子</div><button>根据条件移除类</button><script>$(document).ready(function() {$("button").click(function() {var $box = $("#box");if ($box.hasClass("red")) {$box.removeClass("red"); // 动态判断后移除类}});});</script></body></html>
效果:点击按钮时,如果盒子有 red 类,则移除它。
四、移除所有类
<!DOCTYPE html><html><head><style>.class1 { color: blue; }.class2 { font-size: 20px; }</style><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><p class="class1 class2">这是一个段落。</p><button>移除所有类</button><script>$(document).ready(function() {$("button").click(function() {$("p").removeClass(); // 移除所有类});});</script></body></html>
效果:点击按钮后,段落的所有类(class1 和 class2)都会被移除。
五、结合链式调用
<!DOCTYPE html><html><head><style>.hidden { display: none; }</style><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><div class="hidden">这是一个隐藏的 div。</div><button>显示并添加类</button><script>$(document).ready(function() {$("button").click(function() {$("div").removeClass("hidden") // 移除隐藏类.addClass("visible") // 添加新类.text("现在可见了!"); // 修改文本});});</script></body></html>
效果:点击按钮后,隐藏的 div 会显示,并添加新类 visible,同时文本更新。