第15章 jQuery - CSSクラスの取得と設定
jQuery(ジェイクエリー)は、ウェブブラウザ用のJavaScriptコードをより容易に記述できるようにするために設計されたJavaScriptライブラリである。
homepage
# **jQuery - CSSクラスの取得と設定** *** jQueryにはCSS操作のメソッドがいくつかあります。 * `addClass()` - 選択した要素に1つ以上のクラスを追加します * `removeClass()` - 選択した要素から1つ以上のクラスを削除します * `toggleClass()` - 選択した要素へのクラスの追加/削除を切り替えます * `css()` - スタイル属性を設定または返します ## **addClass()メソッド** 次の例は、クラス属性をさまざまな要素に追加する方法を示しています。もちろん、クラスを追加するときには、複数の要素を選択できます。 #### **例** [sample15-1.html] ``` <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("h1, h2, p").addClass("blue"); $("div").addClass("important"); }); }); </script> <style> .important { font-weight: bold; font-size: xx-large; } .blue { color: blue; } </style> </head> <body> <h1>Heading 1</h1> <h2>Heading 2</h2> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <div>This is some important text!</div><br> <button>Add classes to elements</button> </body> </html> ``` #### **実行結果** <!DOCTYPE html> <pre><span class="nocode"> <iframe src="javascript: '<html><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("h1, h2, p").addClass("blue"); $("div").addClass("important"); }); }); </script> <style> .important { font-weight: bold; font-size: xx-large; } .blue { color: blue; } </style> </head> <body> <h1>Heading 1</h1> <h2>Heading 2</h2> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <div>This is some important text!</div><br> <button style="font-size:inherit">Add classes to elements</button> </body> </html>'" width="800" height="300"></iframe> </span> </pre> *** > **練習** >> **問題**[Ex15-1.html] [sample15-1.html]をもとにして、`toggleClass()`メソッドを練習しましょう。
content
戻る