.removeClass() 與 addClass() 結構相似,核心差異在於「移除」邏輯:將匹配的類名從規築化字符串中 replace 掉,而非拼接。另一關鍵差異:無參數時清空所有類名。
jQuery.fn.extend({
removeClass: function(value) {
var classes, elem, cur, clazz, j, finalValue,
i = 0, len = this.length,
// 關鍵差異:無參數(value 為 undefined)時 proceed 為 true,表示清空所有類
proceed = arguments.length === 0 || typeof value === 'string' && value;
if (jQuery.isFunction(value)) {
return this.each(function(j) {
jQuery(this).removeClass(value.call(this, j, this.className));
});
}
if (proceed) {
classes = (value || '').match(rnotwhite) || [];
for (; i < len; i++) {
elem = this[i];
cur = elem.nodeType === 1 && (elem.className ?
(' ' + elem.className + ' ').replace(rclass, ' ') : '');
if (cur) {
j = 0;
while ((clazz = classes[j++])) {
// 核心差異:循環替換移除所有匹配的類名
while (cur.indexOf(' ' + clazz + ' ') >= 0) {
cur = cur.replace(' ' + clazz + ' ', ' ');
}
}
// 關鍵差異:無參數時 finalValue 為空字符串,否則 trim 結果
finalValue = value ? jQuery.trim(cur) : '';
if (elem.className !== finalValue) {
elem.className = finalValue;
}
}
}
}
return this;
}
});
| 特性 | addClass | removeClass |
|---|---|---|
| 無參數行為 | 無操作 (proceed=false) | 清空所有類 (proceed=true) |
| 類名處理 | cur += clazz + ' '; 拼接 | cur.replace(' ' + clazz + ' ', ' ') 替換 |
| 最終值 | jQuery.trim(cur) | value ? jQuery.trim(cur) : '' |
<div class="a b c"></div>
$('div').removeClass(); // class="" (清空所有)
$('div').removeClass('a b'); // class="c" (移除指定)
$('div').removeClass(function(i, cls) {
return cls.split(' ')[0]; // 移除第一個類
}); // class="b c"
// 移除單個/多個
el.classList.remove('a', 'b', 'c');
// 切換
el.classList.toggle('active');
// 清空所有 (無直接方法)
el.className = '';
// 或
el.removeAttribute('class');