【问题标题】:Less variables in comments评论中的变量更少
【发布时间】:2016-03-03 16:27:03
【问题描述】:

我需要在类的正上方生成一些带有一些 cmets 的 CSS,在这些 cmets 中,我需要评估一些变量。我在 Sass 中成功地做到了这一点,但 Less 似乎没有相同的功能。

这是我需要的:

/**Header*/
.Header {
  font-size: 1.5em;
}

这是我在 Sass 中的尝试:

@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);

  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }

  @return $string;
}

@mixin rte_property($name) {
  /**#{$name}*/
  .#{str-replace($name, ' ', '')} {
    @content;
  }
}

@include rte_property(Header) {
  font-size: 1.5em;
}

这是我在 Less 中的尝试:

.rte_element (@name, @rules) {
    @className: e(replace(@name, " ", ""));
    /**@{name}*/
    .@{className} {
        @rules();
    }
}

.rte_element("Header 2", {
    font-size: 1.5em;
});

Less 是否可以在 cmets 中插值/评估变量?如果有,怎么做?

【问题讨论】:

  • 据我所知不可能有两个原因 - (1) Less 不计算 cmets 内的变量 (2) Less 编译器不允许在选择器块之外打印属性值对(因为它是无效的 CSS),因此甚至无法通过将注释打印为属性 + 值来进行修改。

标签: less


【解决方案1】:

在 Less 中没有直接(非 hacky)的方式来实现这一点。 Less 编译器不会评估 cmets 中存在的任何变量,因此它将继续打印为 @{var} 而不是评估值。

但是,这并不意味着根本没有办法。有一种方法可以实现接近的目标。那就是将整个注释文本放入一个临时变量中,并使用选择器插值技术在选择器之前打印它。

该注释不会对编译后的 CSS 的工作方式产生任何影响(因为 UA 将忽略 cmets,请参阅最后的 sn-p - 它使用此代码生成的编译后的 CSS)但它不会换行。

注意:绝对不推荐实施这种骇人听闻的解决方案。我在这里给出它只是为了表明它可以以不同的方式完成。

更少的代码:

.rte_element(@name, @rules) {
  @className: e(replace(@name, " ", ""));
  @comment: ~"/* @{name} */"; /* store the comment structure as a variable */
  @{comment}  .@{className} { /* print it before the selector */
    @rules();
  }
}

.rte_element("Header 2", {
  font-size: 1.5em;
  color: red;
});
.rte_element("Header 3", {
  font-size: 1.75em;
  color: blue;
});

带有编译 CSS 的演示:

/* Header 2 */ .Header2 {
  font-size: 1.5em;
  color: red;
}
/* Header 3 */ .Header3 {
  font-size: 1.75em;
  color: blue;
}
<div class="Header2">Header 2 text</div>
<div class="Header3">Header 3 text</div>

注释后换行的代码:

这更骇人听闻,但它seems to work in the latest compiler

.rte_element(@name, @rules) {
  @className: e(replace(@name, " ", ""));
  @comment: ~"/* @{name} */
" ;   /* note how there is a line break inside the quotes */
  @{comment} .@{className} {
    @rules();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多