我在 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。
方法二
.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/