Select last child when odd, 2 last childs when even

后端 未结 3 960
失恋的感觉
失恋的感觉 2020-12-31 14:01

I\'m in a situation where the number of elements showed is variable, and I need a strange solution which I\'m not able to achieve, I even doubt if it\'s achievable only with

相关标签:
3条回答
  • 2020-12-31 14:27

    Absolutely it can be done, with pure CSS. See the complete code below (odd child, last child red; even childs, last 2 childs green)

    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $('#but1').click(function(){
                var count = $('p').length; 
                if (count%2!=0) {$('div>p:last-child').css('background','red');}
                else {$('div>p:last-child').css('background','green');alert(count);
                    $('div>p:nth-last-child(2)').css('background','green');
                }
            });
        });
    </script>
    </head>
    <body>
    <button id=but1>Click</button>
    <div>
    <p>This is one.     </p>
    <p> This is two.    </p>
    <p> This is three.  </p>
    <p> This is four.   </p>
    <p> This is five.   </p>
    <p> This is six.    </p>
    </div>
    </body>
    </html>
    

    Enjoy, the coding ;)

    0 讨论(0)
  • 2020-12-31 14:36

    You can use CSS like so:

    li:last-child:nth-child(odd) {
        /* Last child AND odd */
        background: red;
    }
    
    li:nth-last-child(2):nth-child(odd),
    li:last-child:nth-child(even) {
        /* Before last child AND odd */
        /* Last child AND even */
        background: green;
    }
    

    Demo: https://jsfiddle.net/hw0ehrhy/

    0 讨论(0)
  • 2020-12-31 14:43

    Here is one way...

    .wrap div:last-child,
    .wrap div:nth-last-of-type(-n+2):not(:nth-child(even)) {
        color: red;
    }
    <div class="wrap">
        <div>Odd</div>
        <div>Even</div>
        <div>Odd</div>
        <div>Even</div>
        <div>Odd</div>
        <div>Even</div>
    </div>
    
    <hr>
    
    <div class="wrap">
        <div>Odd</div>
        <div>Even</div>
        <div>Odd</div>
        <div>Even</div>
        <div>Odd</div>
    </div>

    0 讨论(0)
提交回复
热议问题