我已经在jquery中看到了这个答案,但是我想知道如何在javascript中做到这一点。到目前为止,我想到了以下内容,但我知道它不能正确捕获nameF.value。



var nameF = document.getElementById("name-field");

var formButton = document.getElementById("form-button");

function go() {
  if (nameF.value == "") {
    formButton.classList.add("notclickable");
  }
}

go();

#form-button {
  cursor: pointer;
  outline: none;
  border: none;
  font-family: $body-font;
  font-size: 14px;
  padding: 16px;
  color: #fff;
  font-weight: 800;
  background-color: #000;
  position: relative;
  border-radius: 2px;
  opacity: 1;
}

#form-button.notclickable {
  opacity: .1;
  pointer-events: none;
}

<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button">
https://stackoverflow.com/questions/ask#





没有jQuery,仅使用香草,该怎么办?

谢谢!

最佳答案

您所需要做的就是将事件处理程序分配给nameF,并将其分配给该类而不是.toggle()

add()接收一个可选的第二个参数,您在其中告诉它是否应添加或删除该类,因此您将在此处传递字符串比较。



var nameF = document.getElementById("name-field");

var formButton = document.getElementById("form-button");

function go() {
  formButton.classList.toggle("notclickable", nameF.value == "");
}

go();

nameF.addEventListener("input", go);

#form-button {
  cursor: pointer;
  outline: none;
  border: none;
  font-family: $body-font;
  font-size: 14px;
  padding: 16px;
  color: #fff;
  font-weight: 800;
  background-color: #000;
  position: relative;
  border-radius: 2px;
  opacity: 1;
}

#form-button.notclickable {
  opacity: .1;
  pointer-events: none;
}

<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button"> https://stackoverflow.com/questions/ask#





另外,请注意,您不需要类即可禁用该按钮。您可以将.toggle()属性与disabled选择器一起使用。这也将禁用其功能,而不仅仅是使其褪色。



var nameF = document.getElementById("name-field");

var formButton = document.getElementById("form-button");

function go() {
  formButton.disabled = nameF.value == "";
}

go();

nameF.addEventListener("input", go);

#form-button {
  cursor: pointer;
  outline: none;
  border: none;
  font-family: $body-font;
  font-size: 14px;
  padding: 16px;
  color: #fff;
  font-weight: 800;
  background-color: #000;
  position: relative;
  border-radius: 2px;
}

#form-button:disabled {
  opacity: .1;
  pointer-events: none;
}

<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button"> https://stackoverflow.com/questions/ask#

关于javascript - 当field.value为空时禁用输入按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47367533/

10-11 12:58
查看更多