如果变量大于 javascript 中的 x,则向元素添加一个类

我有一个带有 id 的元素counter


我还有一个名为abacus


当 abacus 的值大于x - 我希望将一个 CSS 类添加到具有 id `counter 的元素


var abacus = 8


  if (abacus > 5) {

    document.getElementById("counter");

    element.classList.add("greater");

  }


  else {

    document.getElementById("counter");

    element.classList.add("less");

  }

<div id="counter">

</div>

但是,当我运行此代码时,未应用 css 类。



三国纷争
浏览 61回答 2
2回答

慕盖茨4494581

function check_number(){&nbsp; &nbsp;var abacus = 8&nbsp; &nbsp;var num = document.getElementById("num").value&nbsp; &nbsp;if (abacus > num) {&nbsp; &nbsp; &nbsp; var element = document.getElementById("counter");&nbsp; &nbsp; &nbsp; element.classList.add("blackBG");&nbsp; &nbsp;}&nbsp; &nbsp;else {&nbsp; &nbsp; &nbsp; &nbsp;var element = document.getElementById("counter");&nbsp; &nbsp; &nbsp; &nbsp;element.classList.remove("blackBG");&nbsp; &nbsp;}}.blackBG {&nbsp; &nbsp; &nbsp; &nbsp; background-color:#c79d9d;&nbsp;}<div id="counter">&nbsp; &nbsp; some text</div>&nbsp;&nbsp;<input type="text" id="num"><button onclick="check_number()">click </button>

蛊毒传说

当您访问该元素时,您需要将其分配给一个变量或将附加的 js 链接到它。var abacus = 8&nbsp; if (abacus > 5) {&nbsp; &nbsp; document.getElementById("counter").classList.add("greater");&nbsp; }&nbsp; else {&nbsp; &nbsp; document.getElementById("counter").classList.add("less");&nbsp; }<div id="counter"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript