Html 元素不在同一父元素中时奇偶css选择器
在页面中,我们有8个图像,它们可能位于DOM中的任何位置(非常复杂的逻辑,与手头的问题无关)。我想要的是偶数图像的边框为蓝色,奇数图像的边框为红色 我已经试过了,但没有一个有效Html 元素不在同一父元素中时奇偶css选择器,html,css,Html,Css,在页面中,我们有8个图像,它们可能位于DOM中的任何位置(非常复杂的逻辑,与手头的问题无关)。我想要的是偶数图像的边框为蓝色,奇数图像的边框为红色 我已经试过了,但没有一个有效 .timeline-details-image:nth-of-type(even) img { border: 2px solid blue; } .timeline-details-image:nth-of-type(odd) img { border: 2px solid red; } .timel
.timeline-details-image:nth-of-type(even) img
{
border: 2px solid blue;
}
.timeline-details-image:nth-of-type(odd) img
{
border: 2px solid red;
}
.timeline-details-image img:nth-of-type(even)
{
border: 2px solid blue;
}
.timeline-details-image img:nth-of-type(odd)
{
border: 2px solid red;
}
发生的事情是,由于这些图像没有共同的父对象,因此每个图像在其父容器中都是奇数的(因为它是父容器中的第一个图像),因此它们最终都会得到红色边框。有人能指出我做错了什么吗?对奇偶图像边框使用JS,如下所示
$(document).ready(function()
{
$(".timeline-details-image:even").css("border", "1px solid #cccccc");
$(".timeline-details-image:odd").css("background", "1ppx solid #ce0000");
}
CSS本身不能为您做到这一点,您需要一些javascript。如果您使用的是jQuery,则可以执行以下操作:
$(document).ready(function() {
$('.timeline-details-image').each(function(index) {
// check if number is even, then apply class 'even'
if (index % 2 === 0) $(this).addClass('even');
});
});
您可以在HTML中为奇数图像添加两个新类timeline details image odd,为偶数图像添加timeline details image偶数 并添加以下CSS:
.timeline-details-image-odd{border: 2px solid red;}
.timeline-details-image-even{border: 2px solid blue;}
根据@124c41的回答和上述评论,该要求适用于: 身体内部的交替图像 答案似乎需要Javascript JQuery看起来像这样
$(document).ready(function() {
$('img').each(function(index) {
// even //
if (index % 2 === 1) $(this).css("borderBottom", "10px solid red");
// odd //
if (index % 2 === 0) $(this).css("borderBottom", "10px solid blue");
});
});
为什么不选择同级的父元素?你能显示你的HTML吗?你是否建议每个父项中的备用图像需要这种样式或
正文中的备用图像?@Paulie\u D:正文中的备用图像最好在项目上设置奇数
或偶数
类,而不是在项目上设置内联CSS。