使用CSS更改输入div焦点上的span div的CSS

Pra*_*ute 2 html css

我想在输入类型的焦点上更改span div的背景图像.我试图改变适当的父类,但它不适合我.任何帮助,将不胜感激.这是我的代码.

.enq-form-section input[name='treat-cat']:hover .enq-form-section .enq-form .tc-img {
  background: #ccc !important;
}
Run Code Online (Sandbox Code Playgroud)
<div class="form-group">
  <span class="tc-img"></span>
  <input type="text" class="form-control" placeholder="Treatment Category" name="treat-cat">
</div>
Run Code Online (Sandbox Code Playgroud)

Pra*_*lia 7

您可以更改的顺序span和input内容都写?如果是这样,那就太容易了.这是一个例子.

.form-control:hover + .tc-img,
.form-control:focus + .tc-img {
  background: red;
}
Run Code Online (Sandbox Code Playgroud)
<div class="form-group">
  <input type="text" class="form-control" placeholder="Treatment Category" name="treat-cat">
  <span class="tc-img">SOME CONTENT IN HERE</span>
</div>
Run Code Online (Sandbox Code Playgroud)

信息

CSS使得无法选择以前的元素或父元素.这样做是有原因的.

如果您无法更改标记,则必须使用JavaScript来定位前一个元素.

假设你有jQuery,你会做如下的事情.

jQuery(".form-control")
.on("focus", function(){
    // set background color on focus
    $(this).prev().css("backgroundColor","tomato");
})
.on("blur", function(){
    // remove background color on blur
    $(this).prev().css("backgroundColor","none");
});
Run Code Online (Sandbox Code Playgroud)