【问题标题】:How to change color of element when sibling is focused?兄弟聚焦时如何更改元素的颜色?
【发布时间】:2021-05-14 09:54:59
【问题描述】:

当输入聚焦时,我试图更改输入中的小 svg 颜色,但我不知道如何正确定位它。在 devtools 中,我可以直接更改 label 或 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 来写,没关系。

【问题讨论】:

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


    【解决方案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 的。

    【讨论】:

      猜你喜欢
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 2014-06-18
      • 2017-04-25
      相关资源
      最近更新 更多