gpt4 book ai didi

jquery - 将动态变量从 HTML 传递到 less.css 文件

转载 作者:太空狗 更新时间:2023-10-29 12:32:09 25 4
gpt4 key购买 nike

我刚刚开始使用 Less。我现在希望根据从 HTML 文件传递​​的值更改背景颜色。例如在 HTML 文件中选择蓝色而不是所有背景设置为蓝色,如果选择黄色则所有背景设置为黄色。

机制是改变外观和填充的颜色。用户可以根据自己的要求更改主题。因此,当用户更改颜色时,站点颜色的所有主题都应更改。下面是我想传递所选颜色的方式

In this snapshot Html Select blue Color

这就是我希望在 less.css 文件中分配值的方式。

In this snapshot less file description

那么,我怎样才能实现这个场景呢?

最佳答案

我建议您执行以下操作:

  • 为用户提供一个预定义的主题颜色列表以供选择(可能是下拉菜单)。不允许输入他们想要的任何颜色,那会很痛苦。
  • When the select any color append, the color name to the body as a class using jQuery/JS.
  • 在 Less 中,编写以下代码,静态编译并将编译后的 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>


或者,如果您坚持通过前端动态执行此操作,则可以使用 modifyVars 选项:

请注意,我不建议将此选项作为 Less website itself states that it should be used only when there is no other choice .

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;

Plunker Demo (无法将其放入片段中)

关于jquery - 将动态变量从 HTML 传递到 less.css 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37519106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com