加号选择器(+)用于选择下一个相邻同级。

前一个兄弟姐妹是否有同等的?


当前回答

没有这样的选择器,但在DOM API中有一个非常只读的属性

Node.previousSibling节点

其他回答

这是类似问题的链接

CSS选择所有以前的兄弟姐妹以获得星级

因此,我使用每个人的回答来发布我的解决方案,任何人都可以将其作为参考,并可能提出改进建议。

//仅用于检查输入值//Consts公司const starRadios=document.querySelectorAll('input[name=“rating”]');//事件监听器starRadios.forEach((radio)=>radio.addEventListener('change',getStarRadioValue));//获取星形无线电值函数getStarRadioValue(事件){警报(event.target.value)//用它做点什么};.星级{字体大小:1.5rem;unicode bidi:bidi覆盖;方向:rtl;文本对齐:左侧;}.star-rating.editable标签:悬停{光标:指针;}.star-rating.editable.icon星形:悬停,.star-rating.editable.icon星形:悬停~.icon星形{背景色:#fb2727!重要的}.icon星形{位置:相对;背景色:#72747d;宽度:32px;高度:32px;显示:内联块;过渡:背景色0.3s;}.icon-star填充{背景色:#fb2727;}.icon星形>标签{显示:内联块;宽度:100%;高度:100%;左:0;顶部:0;位置:绝对;}.icon star>标签>输入[类型=“radio”]{位置:绝对;顶部:0;左:0;变换:translateY(50%)translateX(50%);显示:无;}<div class=“星级可编辑”><span class=“icon star”><标签><input type=“radio”name=“rating”value=“5”/></label></span><span class=“icon star”><标签><input type=“radio”name=“rating”value=“4”/></label></span><span class=“icon star”><标签><input type=“radio”name=“rating”value=“3”/></label></span><span class=“icon star”><标签><input type=“radio”name=“rating”value=“2”/></label></span><span class=“icon star”><标签><input type=“radio”name=“rating”value=“1”/></label></span></div>

对于我的用例,需要更改焦点上的先前元素样式,并且悬停在父元素中只有两个项。为此,使用了:focuswithin和:hover伪类。

无论何时发生聚焦/悬停事件,都可以选择

.root元素:悬停.element到样式{background color:red;}.root元素:将焦点放在.element中,以设置样式{background color:green;}<div class=“root元素”>文本聚焦</span><input type=“text”placeholder=“type To Style”/></div>

虽然没有以前的CSS选择器。我找到了一个快速而简单的方法来自己选择一个。以下是HTML标记:

<div class="parent">
    <div class="child-1"></div>
    <div class="child-2"></div>
</div>

在JavaScript中,只需执行以下操作:

document.querySelector(".child-2").parentElement.querySelector(".child-1")

这将首先选择父div,然后从child-2 div中选择child-1 div。

如果您使用jQuery,只需执行以下操作:

$(".child-2").prev()

我也有同样的问题,但后来我有了“嘘”的一刻。而不是写作

x ~ y

y ~ x

显然,这与“x”而不是“y”匹配,但它回答了“有匹配吗?”的问题,简单的DOM遍历可能会比javascript中的循环更有效地找到正确的元素。

我意识到最初的问题是一个CSS问题,所以这个答案可能完全不相关,但其他Javascript用户可能会像我一样通过搜索发现这个问题。

我遇到了同样的问题,当我试图更改输入焦点上的前置图标填充颜色时,我的代码看起来像这样:

<template #append>
    <b-input-group-text><strong class="text-danger">!</strong></b-input-group-text>
</template>
<b-form-input id="password_confirmation" v-model="form.password_confirmation" type="password" placeholder="Repeat password" autocomplete="new-password" />

问题是我使用了一个vue引导槽来注入前缀,所以即使我改变了位置,输入后仍然会呈现

嗯,我的解决方案是滑动它们的位置,并添加自定义前缀和使用的~符号,因为css不支持前一个同级。

<div class="form-input-prepend">
    <svg-vue icon="common.lock" />
</div>
<b-form-input id="password_confirmation" v-model="form.password_confirmation" type="password" placeholder="Repeat password" autocomplete="new-password" />

Scss样式

.form-control:focus ~ .form-input-prepend {
    svg path {
        fill: $accent;
    }
}

因此,只需尝试更改其位置,如果需要,请使用css order或position:absolute;以实现您想要的,并避免使用javascript来满足此类需求。