gpt4 book ai didi

html - 将兄弟组合器与 svg 和 :focus 结合使用

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:42 24 4
gpt4 key购买 nike

我刚刚了解了 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>

我可以通过以下方式更改我的 svg 图像的颜色:

path{fill:#f00}

但是,我只想在 .box 中的输入被聚焦时更改颜色。

.box svg path~.box div input:focus{fill:#f00}

因为他们不是直接的 sibling ,所以我使用前缀将他们带到同一级别。

我做错了什么?

最佳答案

如前所述here :

The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.

所以涉及的元素必须有相同的父元素。这不应与“同一祖先”相混淆。 .boxpathinput:focus 的祖先,但不是任何一个的父级。

因此,您通常不会在右侧指定整个 CSS“路径”。这也意味着您不能将 svg 内部的元素与外部的元素配对。

你也有倒序的顺序。假设它完全有效,fill 将应用于 input:focus

四处移动以使其工作并利用其他一些技巧可以得到如下结果:

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>

关于html - 将兄弟组合器与 svg 和 :focus 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39440555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com