2011-09-12 10 views
11

私はSASSを学んだし、私はそれに基づいて@mixinとプロセスへのデータの収集(配列)に合格しようとしている中での使用のためSASSでコレクション(配列)を作成します。@Forループ

 
@mixin roundcorners($collection) { 

    $collectionLength = length(collection); 

    @for($i from 0 to $collectionLength) { 
     border-#{$collection[$i]}-radius: 9px; 
    } 

} 

.mybox { 

    @include roundcorners(['top-right','bottom-left']); 

} 

所望の出力はこのようになります::

 
.mybox { 
    border-top-right-radius: 9px; 
    border-bottom-left-radius: 9px; 
} 

答えて

17

私がいるトラブルはここにいくつかの擬似コードだ@mixin

に値を渡すためにデータ構造を定義していますSASSが配列に持っている最も近いものはリストです。以下のように@eachディレクティブで繰り返すことができます。

@mixin roundcorners($collection: (top-left, top-right, bottom-right, bottom-left), $radius: 0) 
    @each $corner in $collection 
    border-#{$corner}-radius: $radius 

http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#each-directive

私は、ルール自体にリストエントリの値を削除するには、文字列の補間を使用しました - 私はそれが合法だ全くわからないんだけど、私は私のdevの上ではありませんよ。チェックするマシン。

また、引数にデフォルト値を使用しました。つまり、カスタム半径を渡すことができます。リストのどこかを通過すると、デフォルトのリスト全体がクリアされます(これはあなたが望むものだと思っていますが、気をつけるべきことです)。これを行うには

違う、もっと簡単な方法があるかもしれない:デフォルトとして「false」に代わりの0使用

@include rounded(false, 9px, false, 9px) 

@mixin rounded($topLeft:false, $topRight:false, $bottomRight:false, $bottomRight:false) 
    @if $topLeft != false 
    border-top-left-radius: $topLeft 
    @if $topRight != false 
    border-top-right-radius: $topRight 
    @if $bottomRight != false 
    border-bottom-right-radius: $bottomRight 
    @if $topLeft != false 
    border-bottom-left-radius: $topLeft 

デフォルト値を設定することで、あなたは次のように、このミックスインを呼び出すことができます必要以上に半径ルールを作成しないことを意味します。必要に応じて、コーナーをオーバーライドして0半径に戻すこともできます。

+0

おかげで簡潔あなたの生成されたCSSを保ちます!私は '@ each'について知りませんでした。私は' @ for'をどのように使用していたのか非常に好きです!あなたの代わりの解決策は私がやりたいことに適しているようですが、コレクションについても知っておくと良いです!私は検索して検索し、人々がそれが不可能だと言っているだけを見つけることができた。 –

+0

ありがとうございました - あなたのメモごとに補間構文を修正しました。 – Beejamin

3

@Beejaminが提供するコードを使用して、いくつかの構文上の問題を修正した後、以下の解決策を考案できました。

@mixin roundcorners($collection: (top-left, top-right, bottom-right, bottom-left), $radius: 0) { 
    @each $corner in $collection { 
     border-#{$corner}-radius: $radius 
    } 
} 

@include roundcorners((top-right, bottom-left), 9px); 

私は各コーナーに異なる半径を割り当てることができる彼の最終的な解決策を好む。

6

これは私がそれを解決し、異なる半径を設定する方法です。あなたが同じすべての半径を設定することができることを意味し

@mixin border-radius($radius:5px){ 
    @if length($radius) != 1 { 
     $i:1; 
     //covers older modzilla browsers 
     @each $position in (topleft, topright, bottomright, bottomright) { 
      -moz-border-radius-#{$position}:nth($radius, $i); 
      $i:$i+1; 
     } 
     //Covers webkit browsers 
     -webkit-border-radius:nth($radius, 1) nth($radius, 2) nth($radius, 3) nth($radius, 4); 
     //Standard CSS3 
     border-radius: nth($radius, 1) nth($radius, 2) nth($radius, 3) nth($radius, 4); 
    } @else { 
     -webkit-border-radius: $radius; 
     -moz-border-radius: $radius; 
     border-radius: $radius; 
    } 
} 

@include border-radius(5px) 

またはこのような異なる:

@include border-radius((5px, 0, 5px, 0)) 

うまくいけば、あまりにも:)