关注元素之前的状态

问题描述 投票:3回答:1

我在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>
html css accessibility
1个回答
0
投票

方法1

您可以在此处使用focus-within功能。但:focus-within不支持IE。

See browser support list.

方法2

.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>

方法3

当你需要在“: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>
© www.soinside.com 2019 - 2024. All rights reserved.