简体   繁体   English

如何使用带有:hover的nth-child来设置多个子元素的样式?

[英]How to use nth-child with :hover to style multiple children?

JS Fiddle for easier debugging: http://jsfiddle.net/GregsFiddle/WyC7Y/1/ JS Fiddle,可简化调试过程: http//jsfiddle.net/GregsFiddle/WyC7Y/1/

I am trying to setup this css so when you mouseover nine, nine and below get their bg color changed. 我正在尝试设置此CSS,以便当您将鼠标悬停在9、9及以下时,其bg颜色会更改。

Mouseover 5, and 5 and below have their color changed. 鼠标悬停5和5及以下的颜色会更改。 You get the idea. 你明白了。 I am not sure how to use the nth-child(-n+#) selector with :hover. 我不确定如何将nth-child(-n +#)选择器与:hover一起使用。

ol.motivationBox .motivationBars li:nth-child(10):hover:nth-child(-n+9) {
background-color: #008cba;
}

That bit of code is not functioning. 这段代码不起作用。 What did I format incorrectly? 我格式化不正确?

Since you currently can't transverse the DOM tree, this seems to be the only thing possible in pure CSS. 由于您目前无法穿越DOM树,因此这似乎是纯CSS唯一的可能。

Basically, the general sibling combinator, ~ , allows us to access all succeeding sibling elements. 基本上,通用的同级组合器~允许我们访问所有后续的同级元素。

UPDATED EXAMPLE HERE 此处更新示例

ol.motivationBox .motivationBars:hover ~ .motivationBars,
ol.motivationBox .motivationBars:hover {
    background-color: #008cba;
}

.. if you wanted to use jQuery and select preceding sibling elements, you could use this: ..如果您想使用jQuery并选择前面的兄弟元素,则可以使用以下方法:

ALTERNATIVE EXAMPLE HERE 这里的另一个例子

$('.motivationBox .motivationBars').hover(
    function(){
        $(this).prevAll().andSelf().addClass('active');
    },
    function(){
        $('.active').removeClass('active');
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM