2017-05-29 4 views
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; 
    } 

} 

助力のアイデアは素晴らしいと思います。

エミリー

答えて

1

あなたのテストif (isBlue)は冒頭で、一度だけ評価され、青から赤に色が変化onclickリスナーがインストールされています。その後、同じリスナーが常に実行され、色を赤に設定します。

var box = document.querySelectorAll('.box')[0]; 
var isBlue = true; 
box.onclick = function() { 
    if (isBlue) { 
    box.style.background = 'red'; 
    isBlue = false; 
    } 
    else { 
    box.style.background = 'blue'; 
    isBlue = true; 
    } 
} 
+0

おかげユーグ:

代わりに、あなたのif/elseロジック内部の機能を置きます。それが私を怒らせていた。 –

関連する問題