为什么javascript css样式适用于第一个条件但不适用于第二个条件?

时间:2015-07-22 18:28:41

标签: javascript html css

如果输入为空或等于0,内部进度div应该没有背景,我有一个进度条应对输入作出反应。对于所有其他输入,应填写。它适用于输入为空的情况,但输入后输入没有反映。



var first = document.getElementById("first");
if (a.innerHTML == '') {
  first.style.background = "none";
} else {
  first.style.background = "#e91b23";
}

.progress_bars_vertical_holder {
  display: inline-block;
  width: 100%;
  position: relative;
}
.progress_bars_vertical {
  display: inline-block;
  position: relative;
  float: left;
  margin: 0px 2% 0px 0px;
}
.progress_bars_vertical:last-child {
  margin: 0px;
}
.progress_bars_vertical .progress_content_outer {
  height: 200px;
  position: relative;
}

<input id="a" onkeypress="return tisNumberKey(event)" type="text" style="height: 250px; margin-top: 10px; width: 75%; text-align: center; font-size: 100px;" type="text" data-in="" />
<div class="progress_bars_vertical_holder vertical">
  <div class="progress_bars_vertical background_color" style="width: 99.7%;">
    <div class="progress_content_outer">
      <div data-percentage="30" id="first" class="progress_content" style="height: 50%; background-color: rgb(22, 146, 159);"></div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

http://codepen.io/georgiemathews/pen/mJGBOV

2 个答案:

答案 0 :(得分:2)

应该是:

  first.style.background = "#e91b23";
                            ^---

#将该字符串标记为十六进制值。否则它只是被视为一些随机垃圾。

答案 1 :(得分:1)

你有一些错别字。我抓了一份CodePen演示版和here is a working version you can play with

<强> HTML

我开始工作了,当你在框中输入时会添加红色进度条。但是,当你清除input范围时,指标保持红色,因为它只是在寻找按键。我将其更改为oninput以获得所需的行为。

您的功能中也有拼写错误 - 它说tisNumberKey - 更改为isNumberKey

<input id="a" oninput="return isNumberKey(event)" type="text" style="height: 250px; margin-top: 10px; width: 75%; text-align: center; font-size: 100px;" type="text" data-in="" />

<强>的JavaScript

你没有用任何东西调用该函数。 HTML试图调用脚本,但没有命名函数。将function isNumberKey(event)添加到脚本允许它在您输入input范围时运行。

最后,我改变了添加类的逻辑。如果该字段不为空,请将其设置为红色。与其他变化更加一致。工作脚本如下:

function isNumberKey(){
var first =  document.getElementById("first");
var a = document.getElementById("a");
 if (a.value !== '') {
  first.setAttribute("class", "red-bg");
 } else {
  first.setAttribute("class", "no-bg");
 }
}
相关问题