How to iterate through a double for loop in Stylus

2019-09-13 19:16发布

I'm trying to use a double for loop to create 16 css selectors that shift a background-position through each one in a grid. I have the background-position printing correctly, but I can get the class to spit out 1-16. In the example below, index would be replace by the correct solution.

I tried creating a variable and adding one each time through the loop, but it returns and error.

for row in 1 2 3 4
  for col in 1 2 3 4
    li.item{index}
      background-position (((row - 1) * 130 + ((row - 1) * 2)) * -1px) (((col - 1) * 130 + ((col - 1) * 2)) * -1px)

so that you get

li.item1 {
  background-position:0 0;
}
li.item2 {
  background-position:0 -132px;
}
li.item3 {
  background-position:0 -264px;
}
li.item4 {
  background-position:0 -396px;
}
li.item5 {
  background-position:-132px 0;
}
...
li.item16 {
  background-position:-396px -396px;
}

1条回答
Root(大扎)
2楼-- · 2019-09-13 19:38

So, I guess this is more of a Computer Science 101 question, but I figured it out.

for row in 1 2 3 4
    for col in 1 2 3 4
        index = ((row - 1) * 4) + col
        li.item{index}
            background-position (((row - 1) * 130 + ((row - 1) * 2)) * -1px) (((col - 1) * 130 + ((col - 1) * 2)) * -1px)
查看更多
登录 后发表回答