Use function/mixin in Less selector

2019-07-28 03:02发布

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条回答
神经病院院长
2楼-- · 2019-07-28 03:22

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

查看更多
登录 后发表回答