如果输入为空,则添加和删除类

时间:2018-12-14 18:23:27

标签: javascript html

输入为空时,我在添加和删除类时遇到问题。

代码也可以在JSFiddle上使用。

Install-Package VideoLibrary -Version 2.0.3
var name = document.getElementById("name").value;
var lastname = document.getElementById("lastname").value;
var underlineFocus = document.getElementsByClassName("underline-focus");

function changeUnderline() {
  if (name === "") {
    underlineFocus[0].classList.add("underline-focus-empty");
  } else {
    underlineFocus[0].classList.remove("underline-focus-empty");
  }
  if (lastname === "") {
    underlineFocus[1].classList.add("underline-focus-empty");
  } else {
    underlineFocus[1].classList.remove("underline-focus-empty");
  }
}
changeUnderline();
form {
  justify-content: flex-start;
  align-content: flex-start;
  align-items: flex-start;
}

input {
  width: 100%;
  height: 24px;
  font-size: 14px;
  background: none;
  border: none;
  outline: none;
}

.underline {
  width: 100%;
  height: 1px;
  margin-bottom: 18px;
  background-color: #1a2c5b;
  position: relative;
  top: -3px;
}

.underline-focus {
  width: 0;
  height: 3px;
  background-color: #7971ea;
  transition: width .3s ease-in-out;
  z-index: 10;
}

input:focus+.underline-focus {
  width: 100%;
}

.underline-empty,
.underline-focus-empty {
  background-color: #f95959;
}

我已经看过其他问题,找不到答案。

1 个答案:

答案 0 :(得分:0)

您的代码中有2个主要错误。
1)使用<form>每个回车将您的数据发送到任何地方,并将所有输入刷新为null
2)您不能在变量中使用“名称”一词。

var X_name = document.getElementById("name");
var underlineFocus = document.getElementsByClassName("underline-focus");

function changeUnderline() {

  if (X_name.value === "") {
    underlineFocus[0].classList.add("underline-focus-empty");
  } else {
    underlineFocus[0].classList.remove("underline-focus-empty");
  }
}
changeUnderline();
form {
  justify-content: flex-start;
  align-content: flex-start;
  align-items: flex-start;
}

input {
  width: 100%;
  height: 24px;
  font-size: 14px;
  background: none;
  border: none;
  outline: none;
}

.underline {
  width: 100%;
  height: 1px;
  margin-bottom: 18px;
  background-color: #1a2c5b;
  position: relative;
  top: -3px;
}

.underline-focus {
  width: 0;
  height: 3px;
  background-color: #7971ea;
  transition: width .3s ease-in-out;
  z-index: 10;
}

input:focus+.underline-focus {
  width: 100%;
}

.underline-empty,
.underline-focus-empty {
  background-color: #f95959;
}
  <!--form -->
    <label for="name">Name *</label>
    <input type="text" name="name" id="name" onchange="changeUnderline();" required>
    <div class="underline-focus"></div>
    <div class="underline"></div>
  <!--/form -->