当兄弟姐妹聚焦时如何改变元素的颜色?

时间:2021-02-10 17:03:49

标签: html css user-interface sass css-selectors

当输入聚焦时,我试图更改输入中的小 svg 的颜色,但我不知道如何正确定位它。在 devtools 中,我可以直接更改标签颜色或 svg,它们都可以工作。

<form action="" className="search-bar input-wrapper" onSubmit={(e) => handleSubmit(e)}>
        <input
            type="text"
            className="input"
            id="search-bar-input"
            placeholder="Search..."
            value={searchbar}
            onChange={(e) => handleChange(e)}
            onKeyDown={(e) => handleKeyDown(e)}
        />

        <label id="input-label" htmlFor="search-bar-input">
            <VscSearch id="input-icon" className="input-icon" />
        </label>
    </form>

我尝试过但没有用的东西:

#search-bar-input:focus ~ #input {
color: red;
}

#search-bar-input:focus + #input {
color: red;
}

#search-bar-input:focus ~ #input-icon {
    color: blue;
}

#search-bar-input:focus + #input-icon {
    color: blue;
}

.search-bar {
    &:focus {
        #input-label {
            color: yellow;
        }
        #input-label {
            svg {
                color: orange;
            }
        }

        #input-icon {
            color: green;
        }
    }
}

我可以用 sass 或 CSS 写这个,没关系。

1 个答案:

答案 0 :(得分:1)

您可以使用 adjacent sibling combinator (+) 或 the general sibling combinator (~):

#search-bar-input:focus + #input-label-1 {
   /* Only works if #input-label-1 immediately follows #search-bar-input */
   color: red;
}

#search-bar-input:focus ~ #input-label-2 {
   color: blue;
}
<input
   type="text"
   id="search-bar-input"
   placeholder="Search..."
/>

<label id="input-label-1">
   <i>Red</i>
</label>

<label id="input-label-2">
   <i>Blue</i>
</label>


至于你尝试了什么:

#search-bar-input:focus ~ #input
#search-bar-input:focus + #input

这些无法工作,因为您没有任何名为 #input 的 ID。

#search-bar-input:focus ~ #input-icon

一般的兄弟组合器要求两个元素共享同一个父元素。

#search-bar-input:focus + #input-icon

相邻的兄弟组合器要求您的目标元素紧跟在第一个元素之后。


最后,您编译的 SCSS 将是:

.search-bar:focus #input-label {
  color: yellow;
}

.search-bar:focus #input-label svg {
  color: orange;
}

.search-bar:focus #input-icon {
  color: green;
}

由于 .search-bar 没有获得输入的焦点,因此无法使用伪类 :focus 工作。但是,它适用于 :focus-within:

.search-bar:focus-within #input-label {
  color: yellow;
}
<form class="search-bar">
   <input
      type="text"
      id="search-bar-input"
      placeholder="Search..."
   />

   <label id="input-label">
      <i>Yellow</i>
   </label>
</form>

注意这个伪类 is not supported 来自 IE。