2016-02-08 48 views
1

我有以下更少的代码:反向悬停国少

.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 + jQuery是固定的相反混乱/可维护性问题。

回答

2

我真的会推荐像下面这样写,因为它使代码简单易读。

.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,它也可能是别的东西,然后你也可以将它传递给混入作为参数如下图所示:

.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, &[email protected]{addedClass}:hover:after { 
    @rule1(); 
    } 
    &:hover:after, &[email protected]{addedClass}:after { 
    @rule2(); 
    } 
} 

Demo

+1

我没有被绑定到一个mixin的任何特定原因 - 我不相信我只看了它,只要我做了,没有简化sele像你这样的人首先在那里。这正是我需要的,谢谢。 –