2016-01-23 67 views
1
有條件地否定媒體查詢

我有以下的混入(source):在薩斯

@mixin media($queries) { 

    @if length($queries) == 0 { 
    @content; 
    } @else { 
    $first-key: nth(map-keys($queries), 1); 

    @media ($first-key: map-get($queries, $first-key)) { 
     $queries: map-remove($queries, $first-key); 

     @include media($queries) { 
     @content; 
     } 
    } 
    } 
} 

我想用一個條件能夠否定媒體查詢,像這樣:

@media not screen and ($first-key: map-get($queries, $first-key)) { 

什麼是動態添加它的正確語法?我嘗試沒有成功如下:

$invert: true; 
$foo: if($invert, 'not screen and', null); 

@media #{$foo} ($first-key: map-get($queries, $first-key)) { 

錯誤:

Invalid CSS after "[email protected] #{$foo} ": expected "{", was "($first-key: ma..." 

迭代查詢看起來是這樣的:

tablet: (
    respond-to: (min-width: 421px, max-width: 992px) 
) 

使用時會導致下面的CSS:

@media (min-width: 421px) and (max-width: 992px) { } 

回答

1

我d沒有解釋你爲什麼不起作用(this issue聲稱在解析媒體查詢之前完成插值)。

它看起來你需要移動and以外的變量,進入媒體查詢本身:

@mixin media($queries, $invert: false) { 
    @if length($queries) == 0 { 
    @content; 
    } @else { 
    $first-key: nth(map-keys($queries), 1); 

    $foo: if($invert, 'not', '') screen; 
    @media #{$foo} and ($first-key: map-get($queries, $first-key)) { 
     $queries: map-remove($queries, $first-key); 

     @include media($queries, $invert) { 
     @content; 
     } 
    } 
    } 
} 

輸出:

@media not screen and (min-width: 30em) and (max-width: 50em) { 
    .foo { 
    color: red; 
    } 
} 

@media (min-width: 30em) { 
    .foo { 
    color: green; 
    } 
} 

是的,你需要應用not每次嵌套時,否則Sass將不合並媒體查詢(因爲它們彼此獨佔,所以不能合併not screen(min-width: 30em))。

+0

謝謝,非常感謝 – Johan