【问题标题】:How to Change Style of Span When Hovering Input [duplicate]悬停输入时如何更改跨度样式
【发布时间】:2019-10-25 01:28:46
【问题描述】:

我想更改<span /> 的样式,它不是输入的子元素。我试图用+> 找到<span />,但我永远无法改变它。

是否可以用纯css/scss改变它的样式?

#input:hover,
#input:focus-within {
  span { color: red; }
}
<input type="search" id="input" value='' />
<div>
  <span>My colour should change when hovering the input.</span>
</div>

【问题讨论】:

  • 注意:目标重复项在此处作为答案的一部分。

标签: css


【解决方案1】:

使用adjacent siblingchild combinators 之类的:

#input:hover+div>span,
#input:focus-within+div>span {
  color: red;
}
<input type="search" id="input" value='' />
<div>
  <span>My colour should change when hovering the input.</span>
</div>

请注意,子 (&gt;) 组合子不是必需的,但它确保您只选择子跨度,而不是所有跨度后代都应该有其他子代。您也可以使用general sibling combinator (~) 而不是相邻的,但同样,特异性似乎对您的情况更有帮助。

【讨论】:

    【解决方案2】:

    你可以试试这个代码:

    input[type="search"]#input:hover ~ div span {
       color: red; 
    }
    <input type="search" id="input" value='' />
    <div>
      <span>My colour should change when hovering the input.</span>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 2023-03-08
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      相关资源
      最近更新 更多