Dynamically changing less variables

前端 未结 3 1532
北恋
北恋 2020-12-01 06:40

I want to change a less variable on client side. Say I have a less file

@color1: #123456;
@color2: @color1 + #111111;

.title { color: @color1; }
.text { co         


        
3条回答
  •  温柔的废话
    2020-12-01 07:23

    This less:

    @color1: #123456;
    @color2: @color1 + #111111;
    
    .title { color: @color1; }
    .text { color: @color2; }
    

    compiles to this CSS and this is all the browser knows about:

    .title { color: #123456; }
    .text { color: #234567; }
    

    So, now you're effectively saying you want to change dynamically to this:

    .title { color: #ff0000; }
    

    You can do that by reaching into the existing stylesheet with JS and changing the rule for .title. Or, you can define an alternate rule in your original CSS:

    .alternate.title { color: #ff0000; }
    

    And, find all the objects with .title and add .alternate to them. In jQuery, this would be as simple as:

    $(".title").addClass(".alternate");
    

    In plain JS, you'd need to use a shim to provide getElementsByClassName in a cross browser fashion and then use:

    var list = document.getElementsByClassName("title");
    for (var i = 0, len = list.length; i < len; i++) {
        list[i].className += " alternate";
    }
    

提交回复
热议问题