Use function/mixin in Less selector

不羁岁月 提交于 2020-01-25 01:10:17

问题


I need to repeat my selector. is there any way in Less CSS to do this with function/mixin?

Note: Content of frame is different.

.slide1{
  .frame{
     .obj1{}
     .obj2{}
     .obj3{}
  }
  [data-fragment=1].active ~ .frame {
     .obj1{}
     .obj2{}
     /* frame1 css */
  }

  [data-fragment=2].active ~ .frame {
     .obj2{}
     .obj3{}
     /* frame2 css */
  }
  /* other frames ... */
}
.slide2{
  /* slide2 css */
}
/* other slides ... */

to

.slide1{
  .frame{/* ... */}
  .frameselector(1){/* frame1 css */}
  .frameselector(2){/* frame2 css */}
}
.slide2{/* slide2 css */}

回答1:


Yes, you can form the selector dynamically by using a mixin like below. The mixin accepts two parameters out of which one is the frame number for which the selector has to be generated and the other is the set of rules (ruleset) that is applicable for this frame.

Passing Rulesets to Mixins was introduced only in Less v1.7.0 and hence this code would not work with lower versions of the less compiler.

Note: If the properties/rules for all frames had some common pieces this can be reduced further using loops, but since they are different we have to pass the ruleset corresponding to each frame as part of the mixin call.

Less:

.frameselector(@number, @ruleset){
    @sel: ~"[data-fragment = @{number}]";
    @{sel}.active ~ .frame{
        @ruleset();
    }
}
.slide1{
    .frame{
        /* some code */
    }
    .frameselector(1,{
        /* all rules or props belonging to frame 1 */
        color:red;
        background: beige;
    });
    .frameselector(2,{
        /* all rules or props belonging to frame 2 */
        color:green;
        background: white;
    });
}

Compiled CSS Output:

.slide1 .frame {
    /* some code */
}
.slide1 [data-fragment = 1].active ~ .frame {
    color: red;
    background: beige;
}
.slide1 [data-fragment = 2].active ~ .frame {
    color: green;
    background: white;
}

CodePen Demo



来源:https://stackoverflow.com/questions/25986070/use-function-mixin-in-less-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!