Javascript 不会触发 not if nor else

标签 javascript html css

我的 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/

相关文章:

html - 使用类在 CSS 中创建菜单

html - Bootstrap 警报正在扰乱 DOM

javascript - 纯 javascript 到 jquery - clientHeight

javascript - 带有特殊字符的AngularJS表达式

html - 如何分层选择div标签内的一个特定的P标签

javascript - 使用 JavaScript 滚动页面

javascript - 在 topojson 上查找缩放距离

javascript - 究竟如何进行这个循环的进步呢? (兼容Internet Explorer 9,时间准确)

html - 无法找到在原始 html 代码中检查元素中显示的内联样式

css - 提交按钮中的填充值