如何选择不包含隐藏类的第一个和最后一个元素

时间:2015-08-08 20:53:09

标签: html css

我喜欢选择不包含隐藏类的第一个和最后一个元素。

public final void setCallback(Callback cb) {
     mCallback = new WeakReference<Callback>(cb);
}

这对我来说可以捕捉所有元素。

但我如何只获得第一个和最后一个?

   <div class="gallery-cell hidden"></div>
    <div class="gallery-cell hidden"></div>
    <div class="gallery-cell"></div>
    <div class="gallery-cell"></div>
    <div class="gallery-cell"></div>
    <div class="gallery-cell"></div>
    <div class="gallery-cell hidden"></div>
    <div class="gallery-cell hidden"></div>    

纯粹的css会很棒。

2 个答案:

答案 0 :(得分:2)

遗憾的是,仅在CSS中这是不可能的,因为first-childlast-childnth-of-type都无法实现我们正在寻找的目标。以下是JavaScript解决方案。

现场演示:

var notHidden = document.querySelectorAll(".gallery-cell:not(.hidden)");
notHidden[0].classList.add("targeted");
notHidden[notHidden.length - 1].classList.add("targeted");
.gallery-cell {
    width: 100px;
    height: 100px;
    background-color: black;
    margin: 10px;
}

.targeted {
    opacity:0.2 !important;
}
<div class="gallery-cell hidden"></div>
<div class="gallery-cell hidden"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell hidden"></div>
<div class="gallery-cell hidden"></div>

答案 1 :(得分:0)

您可以使用相邻的兄弟选择器(+)和:not()伪类选择器捕获第一个,如下所示:.gallery-cell.hidden+:not(.hidden)。我没有“last-before ......”的解决方案。

.gallery-cell {
  background-color: lightblue;
  height: 20px;
  border: 1px black solid;
}
.hidden {
  background-color: blue;
}

.gallery-cell.hidden+:not(.hidden){ /* <- This will catch first non-hidden */
  border: 2px green solid;
}
<div class="gallery-cell hidden"></div>
<div class="gallery-cell hidden"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell hidden"></div>
<div class="gallery-cell hidden"></div>