jQuery - CSS クラスの取得と設定
jQuery CSS の操作
jQuery には CSS を操作するためのメソッドがいくつかあります。以下のことを學習します:
addClass() - 選択した要素に 1 つ以上のクラスを追加します
removeClass() - 選択した要素から 1 つ以上のクラスを削除します
toggleClass() - 選択した要素に追加 /クラスを削除します切り替え操作
css() - スタイル屬性を設定または返します
stylesheet
. important
{
font-weight:bold;
font-size :xx-large;
}
addClass() メソッド
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("h1,h2,p").addClass("blue"); $("div").addClass("important"); }); }); </script> <style type="text/css"> .important { font-weight:bold; font-size:xx-large; } .blue { color:blue; } </style> </head> <body> <h1>標題 1</h1> <h2>標題 2</h2> <p>段落1</p> <p>段落2</p> <div>文本</div> <br> <button>為元素添加 class</button> </body> </html>
addClass() メソッドで複數(shù)のクラスを指定することもできます:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").addClass("important blue"); }); }); </script> <style type="text/css"> .important { font-weight:bold; font-size:xx-large; } .blue { color:blue; } </style> </head> <body> <div id="div1">文本。</div> <div id="div2">文本。</div> <br> <button>為第一個元素添加類</button> </body> </html>
removeClass() メソッド
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("h1,h2,p").removeClass("blue"); }); }); </script> <style type="text/css"> .important { font-weight:bold; font-size:xx-large; } .blue { color:blue; } </style> </head> <body> <h1 class="blue">標題 1</h1> <h2 class="blue">標題 2</h2> <p class="blue">段落1</p> <p>段落2</p> <br> <button>從元素中移除 class</button> </body> </html>
oggleClass() メソッド
このメソッドは、選択された要素に対してクラス切り替え操作の追加/削除を実行します:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("h1,h2,p").toggleClass("blue"); }); }); </script> <style type="text/css"> .blue { color:blue; } </style> </head> <body> <h1 class="blue">標題 1</h1> <h2 class="blue">標題 2</h2> <p class="blue">段落1</p> <p>段落2</p> <br> <button>切換 class</button> </body> </html>