2017-03-19 7 views
0

を上下に移動する必要があるJavaScriptコードがあります。私はそれをクリックすると、私はそれが下に行きたい、2回目をクリックすると、それが上がるようにしたい。私のコードはこれです:JavaScriptが実行されない場合は、

function why() 
{ 
    if (document.getElementById("newton").style.bottom == 23) { 
     alert("I entered the IF"); 
     document.getElementById("newton").style.bottom = 0; 
    } 
    else { 
     alert("I entered the ELSE"); 
     document.getElementById("newton").style.bottom = 23; 
    } 
} 

奇妙なことは、最初の時間は、私はそれが上がると私の一部が実行されたELSEに伝えますが、この後、それをクリックすると、任意の効果をもたらすのではないでしょうdiv要素をクリックすることで、それをもう戻りません。どうしてこれなの?

答えて

4

%またはpxなどの単位を指定する必要があります。

function why() { 
 

 
    if (document.getElementById("newton").style.bottom == '23px') { 
 
    alert("I entered the IF"); 
 
    document.getElementById("newton").style.bottom = 0; 
 
    } else { 
 
    alert("I entered the ELSE"); 
 
    document.getElementById("newton").style.bottom = '23px'; 
 
    }; 
 
}
<button id="newton" onclick="why()">click</button>

しかし、私は代わりにクラスを切り替えると、CSSでこの変更を入れてしまうでしょう。

function why(el) { 
 
    el.classList.toggle('up'); 
 
}
#newton { 
 
    bottom: 0; 
 
} 
 
#newton.up { 
 
    bottom: 23px; 
 
}
<button id="newton" onclick="why(this)">click</button>

0

私は他のJS関数が間違っている場合、それは私のコード全体、さらには他の機能に影響を与えることができることが分かりました。コードは正しかったが、別の関数が間違っているためにコードが機能しなくなったため...クラスのアドバイスをGoogleに教えていただきありがとうございます;

関連する問題