如果有健身课程,请更改LESS Mixin吗? [英] Alter LESS Mixin when body class is present?

查看:71
本文介绍了如果有健身课程,请更改LESS Mixin吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个LESS mixin.当某个身体类别存在时,我想更改mixin的一个值.

I have a LESS mixin. When a certain body class is present I want to alter one value of the mixin.

.my-style() {
  font-weight: bold;
  color: red;
}

.my-style-altered() {
  color: blue;
}

.element {
  .my-style;
}

.body-class .element {
  .my-style-altered;
}

这很好.但是我的选择器列表越来越长:

This is working fine. However my list of selectors is getting longer:

.my-style() {
  font-weight: bold;
  color: red;
}

.my-style-altered() {
  color: blue;
}

.element,
.element-2,
.element-3 {
  .my-style;
}

.body-class .element, 
.body-class .element-2,
.body-class .element-3 {
  .my-style-altered;
}

是否有一种更聪明的方式来编写我的选择器列表,所以我不必重复两次?理想情况下,我将只编写一次,并且对于所有它们,如果存在.body-class,则也会应用my-style-altered().

Is there a smarter way of writing my list of selectors so I dont have to repeat them twice? Ideally I would write them once, and for all of them my-style-altered() would be also applied if .body-class is present.

推荐答案

方法1:(针对基本版本和特定于主体类的版本使用不同的mixins)

Method 1: (Using different mixins for the base version and the body-class specific version)

是的,通过将选择器的.body-class *变体嵌套在通用选择器中,并像下面的代码片段一样附加父选择器,可以避免多次编写所有选择器.编译此代码后,Less编译器将自动将&替换为每个父选择器.

Yes, you could avoid having to write all the selectors multiple times by nesting the .body-class * variants of the selector within the generic one and appending the parent selector like in the below snippet. When this code is compiled, Less compiler will automatically replace the & with each one of the parent selectors.

.my-style() {
  font-weight: bold;
  color: red;
}

.my-style-altered() {
  color: blue;
}

.element, .element-2, .element-3 {
  .my-style;
  .body-class &{
      .my-style-altered;
  }
}

已编译的CSS:

.element, .element-2, .element-3 {
  font-weight: bold;
  color: red;
}
.body-class .element,
.body-class .element-2,
.body-class .element-3 {
  color: blue;
}


方法2:(对基本版本和特定于身体类别的版本使用相同的mixin)


Method 2: (Using same mixin for the base version and the body-class specific version)

或者,如果您希望避免使用两个不同的mixin并通过相同的mixin输出两个内容(默认值和.body-class *变体),则可以按照以下步骤进行操作:

Alternately, if you wish to avoid having to use two different mixins and output both the content (the default one and the .body-class * variant) through the same mixin, it can be done like below:

.mixin() {
  font-weight: bold;
  color: red;
    .body-class &{
        color: blue;
    }
}

.element, .element-2 {
  .mixin()
}

这篇关于如果有健身课程,请更改LESS Mixin吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆