現在の要素にactiveクラスを追加する方法
JavaScriptを使用して現在の要素にactiveクラスを追加する方法を学びます。
アクティブ/現在(押下されている)のボタンをハイライト表示する:
アクティブ要素
第1ステップ - HTML を追加:
<div id="myDIV"> <button class="btn">1</button> <button class="btn active">2</button> <button class="btn">3</button> <button class="btn">4</button> <button class="btn">5</button> </div>
第2ステップ - CSS を追加:
/* ボタンのスタイルを設定 */ .btn { border: none; outline: none; padding: 10px 16px; background-color: #f1f1f1; cursor: pointer; } /* active クラス(およびマウスオーバー時のボタン)のスタイルを設定 */ .active, .btn:hover { background-color: #666; color: white; }
第3ステップ - JavaScript を追加:
// 容器要素を取得 var btnContainer = document.getElementById("myDIV"); // 容器内のすべての class="btn" のボタンを取得 var btns = btnContainer.getElementsByClassName("btn"); // ボタンをループして、現在/クリックされたボタンに active クラスを追加 for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); current[0].className = current[0].className.replace(" active", ""); this.className += " active"; }); }
button 要素が最初に active クラスを設定していない場合は、以下のコードを使用してください:
// 容器要素を取得 var btnContainer = document.getElementById("myDIV"); // 容器内のすべての class="btn" のボタンを取得 var btns = btnContainer.getElementsByClassName("btn"); // ボタンをループして、現在/クリックされたボタンに active クラスを追加 for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); // active クラスがない場合 if (current.length > 0) { current[0].className = current[0].className.replace(" active", ""); } // active クラスを現在/クリックされたボタンに追加 this.className += " active"; }); }