2017-03-19 25 views
0

我有JavaScript代碼,必須上移和下移div。當我點擊它時,我希望它上升,然後當我點擊第二次時,我希望它下降。我的代碼是這樣的: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; 
    } 
} 

奇怪的是,我第一次點擊的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功能是錯誤的,它會影響我的整個代碼,甚至其他功能。代碼是正確的,但由於另一個功能是錯誤的,使我的代碼不工作......感謝谷歌的班級建議,我會執行它;)

相關問題