我正在提供代码的简化版本。说这是我的.html文件:
<div>
<div class="you">Novus ordo seclorum</div>
<div class="you">Novus ordo seclorum</div>
<div class="me">I have a buddy below me.</div>
<div class="me">I have a buddy above me. </div>
<div class="you"> I am a lonely type. Before and after are all 'me'</div>
<div class="me">I have a buddy below me.</div>
<div class="me">I have a buddy above me. </div>
</div>
我想对class="you"
应用特定的.css样式,该样式完全位于中间。 class="you"
的上方和下方都没有元素。
我尝试使用:only-of-type
选择器,但未对元素应用任何样式。
.you:only-of-type {
color: red;
}
那么我如何将某种样式应用于元素上边或下边没有相同class
的元素?
答案 0 :(得分:0)
很遗憾,CSS中没有紧邻上一个元素选择器。
您可以在JavaScript中进行的操作是识别紧随.you
之后的每个.me
(使用+
选择器),然后对它应用.only-you
类也是,后跟.me
。
工作示例:
var meBeforeYous = document.querySelectorAll('.me + .you');
for (var i = 0; i < meBeforeYous.length; i++) {
if (meBeforeYous[i].nextElementSibling.classList.contains('me')) {
meBeforeYous[i].classList.add('only-you');
}
}
.you {
font-weight: bold;
}
.only-you {
color: rgb(255, 0, 0);
}
<div>
<div class="you">I am a you (with a buddy below).</div>
<div class="you">I am a you (with a buddy above).</div>
<div class="me">I have a buddy below me.</div>
<div class="me">I have a buddy above me. </div>
<div class="you"> I am a lonely type. Before and after are both 'me'</div>
<div class="me">I have a buddy below me.</div>
<div class="me">I have a buddy above me. </div>
<div class="you">I am a you (with a buddy below).</div>
<div class="you">I am a you (with a buddy above).</div>
<div class="me">I have a buddy below me.</div>
<div class="me">I have a buddy above me. </div>
</div>