开发者

Determine an elements position in a variable length grid of elements

I have a grid of a variable number of elements. Say 5 images per row and a variable number of images. I need to determine which column (for lack of a better word) each image is in... i.e. 1, 2, 3, 4 or 5.

In this grid, images 1, 6, 12 and 17 would be in column 1 while 4, 9 and 15 would be in column 4.

1  2  3  4  5 
6  7  8  9  10
12 13 14 15 16
17 18 19

What I am trying to do is apply a background image to each element based on it's column position.

An example of this hard coded and inflexible but working perfectly (and if I'm barking up the wrong tree here by all means tell me how you'd ideally accomplish this as it always bugs me when I see someone ask "How do I build a gold plated, solar powered jet pack to get to the top of this building?" when they really should be asking "Where's the e开发者_Python百科levator?"):

switch (imgnum){
                case "1" : case "6" : case "11" :
                    value = "1";
                    break;
                case "2" : case "7" : case "12" :
                    value = "2";
                    break;
                case "3" : case "8" : case "13" :
                    value = "3";
                    break;
                case "4" : case "9" : case "14" :
                    value = "4";
                    break;
                case "5" : case "10" : case "15" :
                    value = "5";
                    break;
                default :
                    value = "";
            }

            $('.someclass > ul').css('background','url("/img/'+value+'.png") no-repeat');

Oh, more info... the value for imgnum in that switch is determined by a click event.


Use the modulus operator for this type of work. The modulus operator gives you the remainder of an integer division. The modulus operator is % in both PHP and JS: http://php.net/manual/en/language.operators.arithmetic.php http://www.java2s.com/Tutorial/JavaScript/0040__Operators/Modulus.htm

You can replace your entire code block with this:

value = imgnum % 5;
if(value == 0) { value = 5; }
$('.someclass > ul').css('background','url("/img/'+value+'.png") no-repeat');


$row_num = int($imgnum/5, PHP_ROUND_HALF_DOWN);

$column_num = (($row_num * 5) - $imgnum)*-1


You can use the jQuery nth child selector, assuming you're doing this on the client:

The index of each child to match, starting with 1, the string even or odd, or an equation ( eg. :nth-child(even), :nth-child(4n) )

The column number would be the index modulo 5.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜