dynamically change LESS variables in page with Jav

2019-06-21 21:17发布

问题:

I'm trying to use less.js to modify LESS variables dynamically with JavaScript. However, I can't seem to get it to work with modifyVars, watch, or refresh.

I tried putting the stylesheet link tag before loading less.js, using less.modifyVars({'@bg': '#00ff00'}), but no change occurs to the background. The less file I'm using is simple:

@bg: #000;
body { background-color: @bg; }

I also tried putting the stylesheet link tag after less.js, as mentioned in this question, and using less.sheets.push($('#less-link')[0]) followed by a call to modifyVars and then refresh. No change in the background color.

I also tried commenting out the @bg: #000; in the LESS file, then setting it via modifyVars. No luck: I end up with a Less::ParseError: variable @bg is undefined.

How can I dynamically change LESS variables and have the page appearance update to reflect those changes?

Edit: hm, this may be some Rails magic happening. When I loaded my less file, the variable definition was gone and all I saw was body { background-color: #000; }. When I switched to using a <style type="text/less"> block of LESS embedded in the page and used this override LESS JavaScript, I was able to change a variable with less.Override('@bg', '#00ff00') and the page's background color immediately changed. Thanks to this answer. Now I'll try it with less.js using the <style> tag instead of <link>.

Edit: looks like less-1.3.3.min.js wants LESS to be loaded in link tags--I get TypeError: Cannot read property 'href' of undefined when I try to use modifyVars and my page looks like this:

<style type="text/less">
@bg: #000;
body {
  background-color: @bg;
}
</style>
<script src="/assets/less-1.3.3.min.js?body=1" type="text/javascript"></script>

回答1:

Instead of doing the variable replacing client-side, since I was doing it in a Rails app anyway, I moved it server-side. I'm using the Ruby bindings for LESS to parse some LESS that includes my custom variables, rendering the parsed result with content_type: 'text/css' and using an AJAX request to add a stylesheet link to the rendered CSS.