2016-02-08 89 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像你這樣的人首先在那裏。這正是我需要的,謝謝。 –