Dynamically changing less variables

醉酒当歌 提交于 2019-11-27 07:30:42
Moin Zaman

The creator of less.js added some features that should allow you to do something like this. Read the comments and the answers here: Load less.js rules dynamically

Marvin, I wrote a function that does exactly what you're looking for, last night.

I have created a fork on Github; https://github.com/hbi99/less.js/commit/6508fe89a6210ae3cd8fffb8e998334644e7dcdc

Take a look at it. Since this is a recent addition, I'd like to hear your comments on the addition. This solution fits my needs perfectly and I think it will do the same for you.

Here is a basic sample;

Sample LESS:

@bgColor: black;
@textColor: yellow;
body {background: @bgColor; color: @textColor;}

From JS:

less.modifyVars({
  '@bgColor': 'blue',
  '@textColor': 'red'
});

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