css - LESS - 在嵌套 Mixin 上使用防护

标签 css less

我正在使用 LESS 处理一组按钮,但遇到了一种似乎无法找到解决方案的情况。基本上,我有一个 mixin 应用于 .button 类,该类具有正常状态和在 mixin 本身内声明的悬停状态。

现在,问题是我想添加一个条件,这样我就不会被迫在 mixin 中应用 &:hover 声明,因此我尝试为@check 变量并在 :hover 状态下使用 when (@check) 但这会产生错误。

我已经将其从原来的 block 中简化了一点,但基本上这代表了我想要做的事情,但似乎找不到实现的正确方法。

._mixin (@color: red, @check: true) {
    background: @color;

    &:hover() when (@check) { // tried &:hover(@check) when (@check) as well
       background: darken(@color, 10%);
    }
}

.button {

    ._mixin(#333);

    &.disabled {
        ._mixin(#333, false);
    }    

}

如何设置 mixin 以根据需要排除 :hover 状态,例如,当 .button.disabled 应用于元素时?

最佳答案

您需要做的是声明 mixin 两次,一次用于所有应应用的样式,一次用于所有需要防护的样式:

//these styles are always applied when ._mixin is used
._mixin (@color: red, ...) {
    background: @color;
}
//these styles are applied only when the second parameter is true
._mixin (@color: red, true) {
    &:hover {
        background: darken(@color, 10%);
    }
}

.button {
    ._mixin(#333);

    &.disabled {
        ._mixin(#333, false);
    }    
}

或者,您可以创建一个带有防护的内部 mixin:

._mixin (@color: red, @guard: true) {
    background: @color;
    //catchall for when the guard doesn't match
    .inner() {}
    //set your styles that you want to match in a guarded inner mixin
    .inner() when (@guard) {
      &:hover {
        background: darken(@color, 10%);
      }
    }
    //apply the inner mixin to the current mixin
    .inner;
}

关于css - LESS - 在嵌套 Mixin 上使用防护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15012625/

相关文章:

javascript - 使所有div.obstacles具有相同的功能

css - 在 django-autocomplete-light 3.1.3 上修改 CSS

c# - 动态渐变

css - 我是否将供应商前缀的 LESS 过于复杂化了?

css - 在 LESS CSS 中从百分比计算宽度到像素然后减去像素

css - 在 css 中带有居中容器的页面范围可重复背景

html - Tailwind CSS - 如何使内容高度适合屏幕

html - GWT 中的触摸调整大小面板

css - lessc 无论如何语法错误

css - Grunt 不再编译 less