在输入:focus上,也将焦点设置为兄弟元素而不使用javascript

时间:2018-12-20 20:29:50

标签: html css html5 css3

我的笔:https://codepen.io/helloworld/pen/XopoYa

当我单击输入控件时,背景会变成灰色。

我想要的是左右列也变灰。

不使用JS怎么可能?

HTML

 <div id="container">
  <div class="column left">
    left
  </div>
  <input type="search" class="column center">

  </input>
  <div class="column right">
  right
  </div>
</div>

CSS

#container {
    display: flex;
    background:orange;
   flex:1;
  width:100%;
  height:50px;
} 

.column.left {
  background:blue;
    width: 230px;
    flex: 0 0 230px;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
  background: red;
}
.column.center {
    border-left: 1px solid #eee;
    flex-grow:1;
  background:white;
  border: 1px blue solid;

}
.column.center:focus{
  background:gray;
}

2 个答案:

答案 0 :(得分:4)

我更改了html代码顺序,并使用order进行了更改。 orderflexbox的属性。

#container {
    display: flex;
    background:orange;
   flex:1;
  width:100%;
  height:50px;
} 

.column.left {
  background:blue;
    width: 230px;
    flex: 0 0 230px;
  order:1;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
  background: red;
  order:3;
}
.column.center {
    border-left: 1px solid #eee;
    flex-grow:1;
  background:white;
  border: 1px blue solid;
  order:2;
  
}
.column.center:focus,
.column.center:focus + .left,
.column.center:focus + .left + .right{
  background:gray;
}
<div id="container">
    <input type="search" class="column center">
    
  </input>
  <div class="column left">
    left
  </div>
  <div class="column right">
  right
  </div>
</div>

答案 1 :(得分:0)

要获得此效果(不更改标记),您需要一个新的伪类 focus-whitin ,该类在现代浏览器(Chrome,Safari,Opera和Firefox)中都受支持

#container {
    display: flex;
    background:orange;
   flex:1;
  width:100%;
  height:50px;
} 

.column.left {
  background:blue;
    width: 230px;
    flex: 0 0 230px;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
  background: red;
}
.column.center {
    border-left: 1px solid #eee;
    flex-grow:1;
  background:white;
  border: 1px blue solid;
  
}
.column.center:focus{
  background:gray;
}
#container:focus-within .left,
#container:focus-within .right{
  background-color: gray;
}
<div id="container">
  <div class="column left">
    left
  </div>
  <input type="search" class="column center">
    
  </input>
  <div class="column right">
  right
  </div>
</div>