0
バニラJSで簡単なクリックトグルを追加したいと思いますが、壁に当たったようです。私は、クリックした後の関数の状態を変更するための変数を作成しましたが、動作していないようです。私は今、私の髪を少し引っ張っています。バニラの状態を変更するためにVarを使用してトグルを作成する方法JS
HTML
<div class="box">Click Me</div>
CSS
.box {
font-family: arial;
letter-spacing: 1px;
display: flex;
justify-content: center;
align-items: center;
height: 200px;
width: 200px;
background-color: blue;
color: white;
}
JS
: https://codepen.io/emilychews/pen/dWByjxコードは、クイックリファレンスのためにここにある:
ペンは、問題を示すために、ここにあります
var box = document.querySelectorAll('.box')[0];
var isBlue = true;
if (isBlue === true) {
box.onclick = function() {
box.style.background = 'red';
isBlue = false;
}
} else {
box.onclick = function() {
box.style.background = 'blue';
isBlue = true;
}
}
助力のアイデアは素晴らしいと思います。
エミリー
おかげユーグ:
代わりに、あなたのif/elseロジック内部の機能を置きます。それが私を怒らせていた。 –