【问题标题】:Reverse states on hover with Less使用 Less 反转悬停状态
【发布时间】:2016-02-08 05:19:06
【问题描述】:

我有以下 LESS 代码:

.favourite-action-link {
    &:after {
        color:@grey;
        content: '\e836';
    }
    &.is-favourite:after {
        color:@red;
        content: '\e811';
    }
    &:hover {
        &:after {
            color:@red;
            content: '\e811';
        }
        &.is-favourite:after {
            color:@grey;
            content: '\e836';
        }
    }
}

基本目标是存在正常状态和悬停状态,当存在另一个类时它们会反转。对于其他操作(例如.share-action-link.review-action-link 等),我将重复此操作,而这看起来很混乱。有没有办法创建一个mixin,这样我就可以像这样提供:

.favourite-action-link {
    &:after {
        color:@grey;
        content: '\e836';
        &:hover {
            color:@red;
            content: '\e811';
        }
        .reverseOnClass(is-favourite);
    }
}

或者类似的东西?到目前为止,我能想到的唯一方法是:

.favourite-action-link {
    &:after {
        color:@grey;
        content: '\e836';
    }
    &.active:after {
        color:@red;
        content: '\e811';
    }
}

然后使用 jQuery 代替悬停 - 在 (isHovering XOR hasClass(is-favourite)) 上切换 .active - 但将 LESS 变为 LESS + jQuery 与修复混乱/可维护性问题相反。

【问题讨论】:

    标签: css less less-mixins


    【解决方案1】:

    我真的建议像下面这样编写它,因为它使代码简单易读。

    .favourite-action-link {
      &:after, &.is-favourite:hover:after {
        color: @grey;
        content: '\e836';
      }
      &:hover:after, &.is-favourite:after {
        color: @red;
        content: '\e811';
      }
    }
    

    但是如果你真的想使用 mixin 来避免重复选择器,那么你可以像下面这样写。此 mixin 将两个规则集作为输入,并将它们应用于所需的选择器。

    .favourite-action-link {
      .rules-gen(
        {
          color: @grey;
          content: '\e836';
        };
        {
          color: @red;
          content: '\e811';
        }
      );
    }
    
    .rules-gen(@rule1; @rule2){
      &:after, &.is-favourite:hover:after {
        @rule1();
      }
      &:hover:after, &.is-favourite:after {
        @rule2();
      }
    }
    

    在这两种方法中,选择器也是分组的,这也意味着减少了代码行数。

    Demo


    或者,如果额外的类并不总是 is-favourite 并且它也可能是其他东西,那么您也可以将它作为参数传递给 mixin,如下所示:

    .favourite-action-link {
      .rules-gen(
        {
          color: grey;
          content: '\e836';
        };
        {
          color: red;
          content: '\e811';
        };
        ~"is-favourite"
      );
    }
    
    .share-action-link {
      .rules-gen(
        {
          color: yellow;
          content: '\e836';
        };
        {
          color: gold;
          content: '\e811';
        };
        ~"active"
      );
    }
    
    .rules-gen(@rule1; @rule2; @addedClass){
      &:after, &.@{addedClass}:hover:after {
        @rule1();
      }
      &:hover:after, &.@{addedClass}:after {
        @rule2();
      }
    }
    

    Demo

    【讨论】:

    • 我并没有因为任何特殊原因被绑定到一个 mixin - 我不敢相信我一直在看它,并且没有像你第一次那样简化选择器。这正是我需要的,谢谢。
    猜你喜欢
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多