根据同级悬停更改同级样式

时间:2018-10-05 09:01:55

标签: css

仅在输入集中且同级悬停时才尝试更改输入的样式:

form#search {
    display: inline-block;
    position: relative;
    min-width: 305px;
    height: 2.500em;
    width: 100%;
    margin: 10px 20px;
    vertical-align: middle;
}

form#search input {
    position: absolute;
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    height: 100%;
    width: 100%;
    padding: 0.5em 5.33em 0.6em 0.33em;
    margin: 0 -2px 0 0;
    border: 2px solid #f2f2f2;
}

form#search input:hover,
form#search input:focus {
    border: 2px solid #005785;
    outline: none;
}

form#search button {
    position: absolute;
    right: 0px;
    width: 5em;
    height: 100%;
    background-color: #005785;
    color: #fff;
    margin: 10px auto;
    padding: 0.33em 1em 0.33em 1em;
    outline: none;
    border: none;
    margin: 0;
    cursor: pointer;
}

form#search button:hover,
form#search button:focus {
    background-color: #003550;
}

form#search input:focus ~ button:hover ~ input:focus {
    border: 2px solid #003550 !important;
}
<form id="search">
  <input type="text">
  <button type="submit">Search</button>
</form>

更具体地说,这一行: form#search input:focus ~ button:hover ~ input:focus

有人知道如何解决此问题吗?似乎没有用,我也不知道逻辑是否合理。

谢谢, 杰米

1 个答案:

答案 0 :(得分:2)

常规的同级选择器(~)仅在DOM中向前搜索。

要获得所需的结果,您必须重新排列按钮和输入的顺序。

您的选择器将变为:

form#search button:hover ~ input:focus

由于只有两个元素,因此可以使用直接同级选择器(+)代替:

form#search button:hover + input:focus

form#search {
    display: inline-block;
    position: relative;
    min-width: 305px;
    height: 2.500em;
    width: 100%;
    margin: 10px 20px;
    vertical-align: middle;
}

form#search input {
    position: absolute;
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    height: 100%;
    width: 100%;
    padding: 0.5em 5.33em 0.6em 0.33em;
    margin: 0 -2px 0 0;
    border: 2px solid #f2f2f2;
}

form#search input:hover,
form#search input:focus {
    border: 2px solid #005785;
    outline: none;
}

form#search button {
    position: absolute;
    right: 0px;
    width: 5em;
    height: 100%;
    background-color: #005785;
    color: #fff;
    margin: 10px auto;
    padding: 0.33em 1em 0.33em 1em;
    outline: none;
    border: none;
    margin: 0;
    cursor: pointer;
    z-index: 1;
}

form#search button:hover,
form#search button:focus {
    background-color: #003550;
}

form#search button:hover ~ input:focus {
    border: 2px solid red !important;
}
<form id="search">
  <button type="submit">Search</button>
  <input type="text">
</form>

我还在按钮上添加了z-index,将其放置在输入的前面。