CSS nth-of-type的奇怪行为

时间:2015-07-10 10:10:32

标签: html css css3

我使用CSS nth-of-type(偶数)来排序div。通常它工作正常,但是当我发出AJAX请求并将新的HTML div放到另一个之后,选择器开始工作很奇怪。

.row > .cd-timeline-block-sort:nth-of-type(even) > .cd-timeline-content {
  float: right;
}

Printscreen of timeline (before)

<div class="cd-timeline-block cd-timeline-block-sort" data-event-id="284">
<div class="cd-timeline-block cd-timeline-block-sort" data-event-id="268">
<div class="cd-timeline-block cd-timeline-block-sort" data-event-id="282">

并在AJAX请求之后:

Printscreen of timeline (after)

<!-- 1 --><div class="cd-timeline-block cd-timeline-block-sort" data-event-id="284">
<!-- 2 --><div class="cd-timeline-block" data-event-id="268" style="display: none;">
<!-- 3 --><div class="cd-timeline-block cd-timeline-block-sort eventForm" id="eventEditForm" style="display: block;">
<!-- 4 --><div class="cd-timeline-block cd-timeline-block-sort" data-event-id="282">

在我的第二个例子中有4个div,其中3个带有.cd-timeline-block-sort类。我需要在左边放(1),在右边放(3),在左边放(4)。

2 个答案:

答案 0 :(得分:2)

显然你想要一个“nth-class”伪选择器which does not exist。由于您使用的是JavaScript,我建议使用以下解决方法:

  1. 从DOM中删除不需要的元素
  2. 如果无法做到这一点,请将不需要的元素的标记名称更改为其他内容:
  3. (1st div) div.cd-timeline-block.cd-timeline-block-sort
    (1st del) del.cd-timeline-block
    (2nd div) div.cd-timeline-block.cd-timeline-block-sort
    (3rd div) div.cd-timeline-block.cd-timeline-block-sort
    

    CSS将是:

    .row > div:nth-of-type(even) { }
    .row > del                   { display: block; }
    
    1. 另一种解决方案是以不同方式对元素进行分组:
    2. (1st div) div.group
                    .cd-timeline-block.cd-timeline-block-sort
      (2nd div) div.group
                    .cd-timeline-block
                    .cd-timeline-block.cd-timeline-block-sort
      (3rd div) div.group
                    .cd-timeline-block.cd-timeline-block-sort
      

      CSS:

      .row > div:nth-of-type(even) { }
      

答案 1 :(得分:0)

您可以使用JQuery找到所需的元素。

// 3rd element with class "cd-timeline-block-sort"
var $block = $('.cd-timeline-block-sort').eq(2);
// Check, whether we found it
if (typeof($block) != 'undefined') {
   // Set CSS styles you need
   $block.css('float', 'right');
}

如果需要,您可以编写更复杂的逻辑。