html - 焦点状态在元素之前

标签 html css accessibility

我在 HTML 中有一个简单的输入元素,它将 $ 添加到输入中,这样它就不会作为输入值的一部分包含在内。为实现这一点,我使用了 CSS,您可以在下面的示例中看到。

我遇到的问题是输入上的焦点状态不适用于 :before 元素,它在 $ 之前,这不是很好出于可访问性的原因。有没有办法用纯 CSS 做到这一点,所以当输入聚焦时它也会使 $ 改变颜色?

input {
  margin: 3em;
  padding-left: 2em;
  padding-top: 1em;
  padding-bottom: 1em;
}

input:focus {
  color: green;
}

.test {
  position: relative;
  background-color: #dedede;
  display: inline;
}

.test:before {
  content: '$';
  position: absolute;
  top: 0;
  left: 40px;
  z-index: 1;
}
<div class="test">
  <input type="text"/>
</div>

最佳答案

方法一

您可以使用 focus-within特色在这里。但是 :focus-within 不支持 IE。

See browser support list.

方法二

.test input {
  padding-left: 2em;
  padding-top: 1em;
  padding-bottom: 1em;
}

.test input:focus,
.test input:focus + label {
  color: green;
}

.test label {
  display: block;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 10px;
  z-index: 1;
}

.test {
  position: relative;
  background-color: #dedede;
  display: inline;
}
<div class="test">
  <input id="input" type="text"/>
  <label for="input">$</label>
</div>

方法三

当您需要处理“:before”选择器时;

.test input {
  padding-left: 2em;
  padding-top: 1em;
  padding-bottom: 1em;
}

.test input:focus,
.test input:focus + label {
  color: green;
}

.test label:before {
  display: block;
  content: '$';
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 10px;
  z-index: 1;
}

.test {
  position: relative;
  background-color: #dedede;
  display: inline;
}
<div class="test">
  <input id="input" type="text"/>
  <label for="input"></label>
</div>

关于html - 焦点状态在元素之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55009558/

相关文章:

javascript - iPad 蓝牙键盘使用 onKeyUp 为任何键返回键码 0

jquery - 使用 jQuery 预加载 CSS Sprite 图像

android - 在 Android 中单击 float 按钮时,如何通过 AccessibilityService 执行滚动事件?

jquery - 父元素可见后,iOS 上的 VoiceOver 不会将焦点放在子元素上

java - 如何自动发送短信?

javascript - 点击图片打开文件上传

html - col-md-2 最后一列不在同一行

javascript - 通过在框外单击关闭下拉菜单

android - 解释 ClickableViewAccessibility

javascript - html Canvas 不清除