[英]Using sibling combinator with svg and :focus
I just learned about the sibling combinator in CSS and I'm trying to shift some of JavaScript operations into CSS but I'm having difficulty. 我刚刚了解了CSS中的同级组合器,并且试图将一些JavaScript操作转换为CSS,但是遇到了困难。
<div class="box">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path d="m64 50-4-8h-6v-4c0-1.1-0.9-2-2-2h-18c-1.1 0-2 0.9-2 2v16l2 2h2.536c-0.341 0.588-0.536 1.271-0.536 2 0 2.209 1.791 4 4 4s4-1.791 4-4c0-0.729-0.196-1.412-0.536-2h11.073c-0.341 0.588-0.537 1.271-0.537 2 0 2.209 1.791 4 4 4s4-1.791 4-4c0-0.729-0.196-1.412-0.537-2h2.537v-6zm-10 0v-6h4.146l3 6h-7.146z"/></svg>
<div><input type="text"></div>
<div><input type="text"></div>
<div><input type="text"></div>
</div>
I'm able to change the color of my svg image with: 我可以使用以下方式更改svg图像的颜色:
path{fill:#f00}
However, I'd only like to change the color if an input in .box is focused. 但是,我只想更改.box中输入的焦点颜色。
.box svg path~.box div input:focus{fill:#f00}
Since they are not directly siblings, I used prefixes to bring them to the same level. 由于它们不是直接的兄弟姐妹,因此我使用前缀将它们带到相同的级别。
What am I doing wrong? 我究竟做错了什么?
The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.
〜组合器分隔两个选择器,并且仅在第二个选择器后面有第二个选择器时才与之匹配,并且两者都共享一个公共父项。
So the involved elements must have the same parent. 因此,涉及的元素必须具有相同的父元素。 This should not be confused with "same ancestor".
这不应与“祖先相同”混淆。
.box
is an ancestor of path
and input:focus
but is not either's parent. .box
是path
和input:focus
的祖先,但两者都不是其父级。
Because of this, you usually don't specify the whole CSS "path" on the right. 因此,通常您不会在右侧指定整个CSS“路径”。 This also means you can't pair an element inside
svg
with an element outside. 这也意味着您无法将
svg
内部的元素与外部的元素配对。
You also have the order backwards. 您也有倒序的订单。 Assuming it worked at all,
fill
would be applied to input:focus
. 假设它完全起作用,则将
fill
应用于input:focus
。
Moving things around to make it work and taking advantage of some other tricks gives something like this: 四处移动以使其正常工作并利用其他一些技巧可以产生以下效果:
input {
display:block;
}
.box input:focus ~ svg {
fill:#f00;
}
<div class="box">
<input type="text">
<input type="text">
<input type="text">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path d="m64 50-4-8h-6v-4c0-1.1-0.9-2-2-2h-18c-1.1 0-2 0.9-2 2v16l2 2h2.536c-0.341 0.588-0.536 1.271-0.536 2 0 2.209 1.791 4 4 4s4-1.791 4-4c0-0.729-0.196-1.412-0.536-2h11.073c-0.341 0.588-0.537 1.271-0.537 2 0 2.209 1.791 4 4 4s4-1.791 4-4c0-0.729-0.196-1.412-0.537-2h2.537v-6zm-10 0v-6h4.146l3 6h-7.146z"/></svg>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.