【问题标题】:Variable interpolation for a media query property in less - missing closing ")"媒体查询属性的变量插值少 - 缺少关闭“)”
【发布时间】:2016-12-03 23:10:11
【问题描述】:

我正在尝试将 sass 函数“翻译”为 less 函数。 这是原始的 SASS 之一:

@mixin bp($feature, $value) {
    // Set global device param
    $media: only screen;

    // Media queries supported
    @if $mq-support == true {

        @media #{$media} and ($feature: $value) {
            @content;
        }

        // Media queries not supported
    } @else {

        @if $feature == 'min-width' {
            @if $value <= $mq-fixed-value {
                @content;
            }
        } @else if $feature == 'max-width' {
            @if $value >= $mq-fixed-value {
                @content;
            }
        }

    }
}

这是我开始在 less 中创建的函数,因为似乎每个声明都无法像在 sass 中一样实现:

.bp(@feature; @val) when (@mq-support = true) {
    @med: ~"only screen";

    @media @{med} and (@{feature}:@val) {
        @content;
    }
}

当我编译这个时,我得到了以下错误:

Missing closing ')' on line 15, column 34:
15     @media @{med} and (@{feature}:@val) {
16         @content;

所以这个错误似乎来自关闭@{feature}右括号,但是根据互联网上的文档和几篇博客文章,似乎自从1.6.0版本的less以来,css属性插值是一个功能应该管用。

有人知道这里可能出了什么问题吗? 是否真的可以在媒体查询中使用变量作为属性?

也许我做错了,但似乎 mixins guard feature in less 与 SASS 和 @if 条件的工作方式不完全相同,因此“翻译”有点不同。

提前谢谢你

塞巴斯蒂安

【问题讨论】:

  • 为什么你的 sass 代码包含的变量更少? @feature 但不是 $feature。
  • @3rdthemagical 我已经替换了变量并错误地粘贴了它......对不起,它应该是 $feature 编辑:我更新了原来的 SASS 函数

标签: css less media-queries


【解决方案1】:

在媒体查询中插值或使用变量在 Less 中的工作方式略有不同。

  • 首先,您不应该使用正常的插值语法 (@{med})。相反,它应该只是@med
  • 接下来,第二个条件也应该设置为一个变量,然后像@med 变量一样附加到媒体查询,或者它应该作为@med 变量本身的一部分包含在内。我在下面提供了两种方法的示例。
.bp(@feature; @val) when (@mq-support = true) {
  @med: ~"only screen and";
  @med2: ~"(@{feature}:@{val})";
  @media @med @med2{
    @content();
  }
}

.bp(@feature; @val) when (@mq-support = true) {
  @med: ~"only screen and (@{feature}:@{val})";
  @media @med {
    @content();
  }
}

下面是将该 Sass 代码完全转换为其 Less 等效代码的示例。 Less不支持Less中的@content,所以应该是passed as a detached ruleset with the mixin call

@mq-support: true;
@mq-fixed-value: 20px;

.bp(@feature; @val; @content) {
  & when (@mq-support = true) {
    @med: ~"only screen and (@{feature}:@{val})";
    @media @med {
      @content();
    }
  }
  & when not (@mq-support = true) {
    & when (@feature = min-width) {
      & when (@val <= @mq-fixed-value){
        @content();
      }
    }
    & when (@feature = max-width) {
      & when (@val >= @mq-fixed-value){
        @content();
      }
    }
  }
}

a{
  .bp(max-width, 100px, { color: red; } );
}
b{
  .bp(min-width, 10px, { color: blue; } );
}

【讨论】:

  • 感谢您的精彩解释!它工作正常,我更好地理解这里发生的事情。字符串的声明是一个很好的解决方法。祝你有美好的一天!
猜你喜欢
  • 2016-11-10
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 2020-05-08
  • 2019-07-07
  • 1970-01-01
相关资源
最近更新 更多