Passing a dynamic variable from HTML to a less.css file

I just started using Less. Now I want to change the background color according to the value passed from the HTML file. For example, in the HTML file, select a blue color than the entire blue background, and select yellow so that the entire background is set to Yellow.

The mechanism is to change the color for appearance and filling. The user can change his theme in accordance with his requirement. Therefore, when the user changes color, the whole theme of the color of the site must be changed. Below I talk about the transmission of the selected color

In this snapshot Html Select blue Color

And this is how I expect the value to be assigned in the less.css file.

In this snapshot less file description

So how can I achieve this scenario?

+4
source share
1

- :

  • (, ). - , , .
  • body class jQuery/JS.
  • "" , CSS .

    body { 
      background-color: red; /* default */
      &.red {background-color: red;} 
      &.green{background-color: green;} 
      &.blue{background-color: blue;}
    }

window.onload = function() {
  document.querySelector('#color-chooser').addEventListener('change', function() {
    document.body.className = this.value;
  });
}
/* compiled CSS based on the Less code provided above */

body {
  background-color: red;
  /* default */
}
body.red {
  background-color: red;
}
body.green {
  background-color: green;
}
body.blue {
  background-color: blue;
}
<label>Select Background Color:</label>
<select id='color-chooser'>
  <option value='red'>Red</option>
  <option value='blue'>Blue</option>
  <option value='green'>Green (Hex)</option>
</select>
Hide result

, , , modifyVars:

, , Less website , , .

HTML:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet/less" type="text/css" href="styles.less" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.1/less.min.js"></script>
</head>
<body>
  <label>Select Background Color:</label>
  <select id='color-chooser'>
    <option value='red'>Red</option>
    <option value='blue'>Blue</option>
    <option value='#0F0'>Green (Hex)</option>
  </select>
  <script type="text/javascript" language="javascript">
    document.querySelector('#color-chooser').addEventListener('change', function(){
      less.modifyVars({ /* this sets the color to the variable */
        '@bgcolor': this.value
      });
    });
  </script>  
</body>
</html>

styles.less:

body {
  background-color: @bgcolor;
}
@bgcolor: red;

- ( )

+5

All Articles