美文网首页
Stylus预处理器简介(十二)迭代控制

Stylus预处理器简介(十二)迭代控制

作者: 曲昶光 | 来源:发表于2021-07-27 09:11 被阅读0次

    迭代控制

    Stylus 允许你使用 for/in 构造迭代表达式,格式如下:

      for <val-name> [, <key-name>] in <expression>
    
    

    例如:

    body
      for num in 1 2 3
        foo num
    
    

    生成:

      body {
        foo: 1;
        foo: 2;
        foo: 3;
      }
    
    

    如下实例展示的是如何使用 <key-name>

      body
        fonts = Impact Arial sans-serif
        for font, i in fonts
          foo i font
    
    

    生成:

        body {
          foo: 0 Impact;
          foo: 1 Arial;
          foo: 2 sans-serif;
        }
    
    

    下面展示的是如何书写普通的 for 循环:

    body
      for num in (1..5)
        foo num
    
    

    生成:

    body {
      foo: 1;
      foo: 2;
      foo: 3;
      foo: 4;
      foo: 5;
    }
    
    

    Usage with strings:

    for num in (1..10)
      .box{num}
        animation: box + num 5s infinite
    
      @keframes box{num}
        0%   { left: 0px }
        100% { left: (num * 30px) }
    
    

    混合(Mixins)

    我们可以在 mixin 中使用循环实现更强大的功能,例如,我们可以把表达式对作为使用插值和循环的属性。 我们可以在mixins中使用迭代来产生强大的功能。例如,我们可以使用插值和迭代将表达式对作为属性应用。

    下面,我们定义 apply(), 根据条件判断是否利用所有的 arguments(参数),这样逗号分隔的参数以及表达式列表参数都能够被支持。

     apply(props)
       props = arguments if length(arguments) > 1
       for prop in props
         {prop[0]} prop[1]
    
     body
       apply(one 1, two 2, three 3)
    
     body
       list = (one 1) (two 2) (three 3)
       apply(list)
    
    

    函数

    Stylus 中的函数也可以包含 for 循环。如下是一些实例:

    求和:

      sum(nums)
        sum = 0
        for n in nums
          sum += n
    
      sum(1 2 3)
      // => 6
    
    

    合并:

      join(delim, args)
        buf = ''
        for arg, index in args
          if index
            buf += delim + arg
          else
            buf += arg
    
      join(', ', foo bar baz)
      // => "foo, bar, baz"
    
    

    后置表达式

    就跟 if / unless 可以利用后置表达式(post-statement)一样,for 也可以。如下是一些使用后置表达式语法的例子:

       sum(nums)
         sum = 0
         sum += n for n in nums
    
       join(delim, args)
         buf = ''
         buf += i ? delim + arg : arg for arg, i in args
    
    

    我们还可以从循环中 return (返回),下面就是一个实例,当 n % 2 == 0 的值为 true 时就返回数值。

     first-even(nums)
       return n if n % 2 == 0 for n in nums
    
     first-even(1 3 5 5 6 3 2)
     // => 6
    

    相关文章

      网友评论

          本文标题:Stylus预处理器简介(十二)迭代控制

          本文链接:https://www.haomeiwen.com/subject/hhzlmltx.html