2016-08-12 140 views
14

如何才能选择没有.hidden类的最后li如何选择没有特定类的最后一个元素?

我有HTML和CSS这样的:

ul li:last-child:not(:first-child):not(.hidden) button { 
 
    background-color: red; 
 
}
<ul> 
 
     <li> 
 
     <button>1</button> 
 
     </li> 
 
     <li> 
 
     <button>2</button> 
 
     </li> 
 
     <li class="hidden"> 
 
     <button>3</button> 
 
     </li> 
 
    </ul>

+0

你想在你的榜样,选择第二李? – 3rdthemagical

+0

这是不可能的。 – 3rdthemagical

+0

我弄错他究竟想要什么? –

回答

11

在当前时刻,有一种能够找到一个元素,然后后跟另一个特定元素没有CSS方式。

可能很快,会有CSS关系伪类:has()这将使你想要的可能。这目前在CSS Selectors Level 4 Draft,并且看起来不太可能在任何浏览器上很快推出。

一个演示在下面,但不要指望它能工作,直到选择器4草案至少在工作草案中。

请留意CanIUse以查看它何时可用。

ul li:has(+ .hidden:last-child), 
 
ul li:last-child:not(.hidden) { 
 
    background: red; 
 
}
<ul> 
 
    <li> 
 
    <button>1</button> 
 
    </li> 
 
    <li> 
 
    <button>2</button> 
 
    </li> 
 
    <li class="hidden"> 
 
    <button>3</button> 
 
    </li> 
 
</ul>


:has()可jQuery中的,所以这里是一个jQuery替代

Read more here from the Official jQuery Docs

$('ul li:has(+ .hidden:last-child), ul li:not(.hidden):last-child').css('background', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li> 
 
    <button>1</button> 
 
    </li> 
 
    <li> 
 
    <button>2</button> 
 
    </li> 
 
    <li class="hidden"> 
 
    <button>3</button> 
 
    </li> 
 
</ul>

-1

:nth:last-child伪选择只能与标签工作并没有其他选择像:notclass但如果总是将只有一个.hiddenli在年底,那么你可以使用像这样的CSS :

li:nth-last-child(2) { background: lightblue; }
<ul> 
 
    <li>1</li> 
 
    <li>2</li> 
 
    <li class="hidden">3 hidden</li> 
 
</ul> 
 

 
<ul> 
 
    <li>1</li> 
 
    <li>2</li> 
 
    <li>3</li> 
 
    <li class="hidden">4 hidden</li> 
 
</ul>

相关问题