我的 JavaScript 代码必须上下移动 div。当我单击它时,我希望它上升,然后当我第二次单击时,我希望它下降。我的代码是这样的:
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时它会往上跳,告诉我执行了ELSE部分,但之后点击它就没有任何效果,它不会回落。这是为什么?
最佳答案
您需要指定一个单位,例如 %
或 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>
关于Javascript 不会触发 not if nor else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42892878/