Jquery - 如何每 4 个 <Divs> 交替一个 :Odd :Even 模式?

Jquery - How to alternate an :Odd :Even pattern every 4 lt;Divsgt;?(Jquery - 如何每 4 个 lt;Divsgt; 交替一个 :Odd :Even 模式?)

本文介绍了Jquery - 如何每 4 个 <Divs> 交替一个 :Odd :Even 模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在布局中制作图案(请参阅附件进行可视化)问题是使用 :odd :even 不起作用.

I'm trying to make a pattern in a layout (see attachment for visualisation) The problem is that using :odd :even doesnt work.

我试图通过使用for 循环"和 if 语句来使其工作,但显然 jquery 不会以这种方式做这些事情.或者也许我应该在文档准备声明之外做它?我厌倦了它,但它不起作用.

I've tried to make it work by using "for loops", and if statements, but obviously jquery doesn't do this stuff in that way. Or maybe i'm supposed to do it outside the document ready statement? I tired that to but it just doesnt work.

如何做到这一点?

重要提示... 这些方块在一页上最多 8 个,并在 Wordpress 中生成,每个方块都是一个帖子.所以不幸的是,我无法按照建议将事物分成几行.

Important note... These squares are max 8 on a page and generated in Wordpress, each square being a post. So I'm not able to divide things into rows as suggested unfortunately.

css:

.thumb_container {
width:274px;
height: 274px;
float: left;
position: relative;
background-color: white;
}

 .thumb_container:nth-child(4n+1) { clear:both; background-color: green } /* green just to see if its working */

jQuery tweek 文件(http://baked-beans.tv/bb/wp-content/themes/bakedbeans/js/jquery.site.tweeks.js)

Jquery tweek file (http://baked-beans.tv/bb/wp-content/themes/bakedbeans/js/jquery.site.tweeks.js)

    $(".thumb_container:nth-child(8n+2), .thumb_container:nth-child(8n+4), .thumb_container:nth-child(8n+5), .thumb_container:nth-child(8n+7)")
.css({"background-color":"#333333"});

HTML 点击 HTML 链接

HTML Click HTML for link

推荐答案

var i = 1;
$('#wrapper > div').each(function()
{
    var isEvenRow = Math.ceil(i / 4) % 2 == 0; // 4 is number of columns
    var isCellAlternate = i % 2 == isEvenRow ? 0 : 1;

    if ( isCellAlternate ) {
        $(this).css("background-color", "#000");
    } else {
        $(this).css("background-color", "#ccc");
    }
    i++;
});​

或可读性较差但较短的版本:

or the less readable but shorter version:

var i = 1;
$('#wrapper > div').each(function() {
    if (i % 2 == (Math.ceil(i / 4) % 2 == 0) ? 0 : 1) $(this).css("background-color", "#000");
    else $(this).css("background-color", "#ccc");
    i++;
});​

基本上你每行更改备用单元格的测试.

essentially you change the test for the alternate cell every row.

这篇关于Jquery - 如何每 4 个 <Divs> 交替一个 :Odd :Even 模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Jquery - 如何每 4 个 <Divs> 交替一个 :Odd :Even 模式?

基础教程推荐