【问题标题】:How to change label color on input focus in pure javascript? [duplicate]如何在纯javascript中更改输入焦点上的标签颜色? [复制]
【发布时间】:2017-10-14 00:00:30
【问题描述】:

我在绝对位置的 div 中有两个输入框。以及这些输入框上的标签。我想要的效果是当我聚焦一个输入框时,标签应该是蓝色的,当模糊时应该删除类(蓝色)。同时还有其他标签和输入框。

// Initial color of label
label.labels{
  color: black;
}

input.box{
  border-width: 0 0 2px 0;
  outline: none;
}
<div style = "position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;">
  <label class = "labels">First Name:</label>
  <input type = "text" class = "box" /><br />
  <label class = "labels">Last Name:</label>
  <input type = "text" class = "box" />
</div>

当我关注 input.box 时,label.labels 颜色应该是蓝色的。是的,输入和标签都有相同的类。如何用纯 Javascript 实现这种效果?或者如果可能,请告诉我如何使用 css 实现这一目标?

【问题讨论】:

  • 不工作的兄弟!
  • 您想同时影响两个标签吗?
  • 您的代码没有正确使用label 元素。它要么需要包装它作为标签的元素,要么需要将for 属性设置为它所针对的元素的id。 label 是 UI 可访问性中的关键元素,应正确使用。

标签: javascript html css


【解决方案1】:

这是一个使用纯 Javascript 的解决方案:

function toggleClass() {
  this.previousElementSibling.classList.toggle('imblue');
}

var inputs = document.getElementsByClassName('box');

for (var i = 0; i < inputs.length; i++) {
  var input = inputs[i];

  input.addEventListener('focus', toggleClass);
  input.addEventListener('blur', toggleClass);
}
label.labels {
  color: black;
}

input.box {
  border-width: 0 0 2px 0;
  outline: none;
}

.imblue {
  color: blue !important;
}
<div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;">
  <label class="labels">First Name:</label>
  <input type="text" class="box" /><br />
  <label class="labels">Last Name:</label>
  <input type="text" class="box" />
</div>

【讨论】:

  • 就是这样!非常感谢!
  • 哇!难以置信的!看来我需要深入研究 Javascript。
【解决方案2】:

使用 :focus-within 伪元素的 css 解决方案。请注意,IE / Edge 不支持此功能。

您需要包装每个 label 和 input 对才能使其工作。

// Initial color of label
label.labels {
  color: black;
}

input.box {
  border-width: 0 0 2px 0;
  outline: none;
}

.field:focus-within .labels {
  color: blue;
}
<div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;">
  <div class="field">
    <label class="labels">First Name:</label>
    <input type="text" class="box" /><br />
  </div>
  <div class="field">
    <label class="labels">Last Name:</label>
    <input type="text" class="box" />
  </div>
</div>

【讨论】:

  • 这是一个很好的解决方案。请记住,它不是普遍支持的:caniuse.com/#search=focus-within
  • 是的!因为并非所有浏览器都支持。对不起,我不能接受这个答案。但这是一个很好的解决方案!
猜你喜欢
  • 2014-02-04
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-02
  • 1970-01-01
  • 2019-03-12
  • 2013-01-02
相关资源
最近更新 更多