押すと色が変わるボタン
クリックしたら色が変わるようなボタンができたので、紹介していきます。
完成コードは以下のとおりです。
See the Pen Untitled by Flandrer5carlet (@Flandrer5carlet) on CodePen.

れいむ
それでは解説していきます!
<button>ボタン要素について
<button type="button" onclick="new Button(this).Hinagata">アリちゃん</button>
<button type="button" onclick="new Button(this).Hinagata">コオロギちゃん</button>
<button type="button" onclick="new Button(this).Hinagata">芋虫ちゃん</button>
ボタン要素にある「onclick=”new Button(this).Hinagata”」でJavascriptのHinagataメソッドを呼んでいます。
constructorメソッド
constructor( value ) {
this.value = value;
}
constructorにクリックしたボタン要素のthisを入れています。
staticメソッド
static styleremove(){ //全button style要素の削除
// //button要素を取得
const elem = document.querySelectorAll('button');
// //style要素を削除
elem.forEach(function(value) {
value.removeAttribute('style');
})
}
静的メソッドであるstatic styleremove()ですべてのボタンのstyle要素を削除しています。
ゲッターメソッド
get Hinagata(){
//全button style要素の削除
Button.styleremove();
//ボタンの色を変更
this.value.style.color='#fff';
this.value.style.background= 'red';
}
ボタンをクリックした際に実行されるget Hinagataは、最初にstyleremove()を呼んで全button style要素の削除をしています。
削除後、style.colorとstyle.backgroundの色を変えています。
コメント