addClass(class)為每個匹配的元素添加指定的類名。
Adds the specified class(es) to each of the set of matched elements.
返回值
jQuery
參數
class (String) : 一個或多個要添加到元素中的CSS類名,請用空格分開
示例
為匹配的元素加上 'selected' 類
HTML 代碼:
<p>Hello</p>
jQuery 代碼:
$("p").addClass("selected");
結果:
[ <p class="selected">Hello</p> ]
為匹配的元素加上 selected highlight 類
HTML 代碼:
<p>Hello</p>
jQuery 代碼:
$("p").addClass("selected highlight");
結果:
[ <p class="selected highlight">Hello</p> ]
------------------------------------------------------------------------------------------------------------------------------
removeClass(class)從所有匹配的元素中刪除全部或者指定的類。
Removes all or the specified class(es) from the set of matched elements.
返回值
jQuery
參數
class (String) : (可選) 一個或多個要刪除的CSS類名,請用空格分開
示例
從匹配的元素中刪除 'selected' 類
HTML 代碼:
<p class="selected first">Hello</p>
jQuery 代碼:
$("p").removeClass("selected");
結果:
[ <p>Hello</p> ]
刪除匹配元素的所有類
HTML 代碼:
<p class="selected first">Hello</p>
jQuery 代碼:
$("p").removeClass();
結果:
[ <p>Hello</p> ]
------------------------------------------------------------------------------------------------------------------------------
toggleClass(class)如果存在(不存在)就刪除(添加)一個類。
Adds the specified class if it is not present, removes the specified class if it is present.
返回值
jQuery
參數
class (String) :CSS類名
示例
為匹配的元素切換 'selected' 類
HTML 代碼:
<p>Hello</p><p class="selected">Hello Again</p>
jQuery 代碼:
$("p").toggleClass("selected");
結果:
[ <p class="selected">Hello</p>, <p>Hello Again</p> ]
新聞熱點
疑難解答
圖片精選