如何使用javascript / jquery在less css中更改主题颜色

我用下面的css来改变不同的主题颜色

@lightRed: #fdd; @lightGreen: #dfd; @lightBlue: #ddf; @defaultThemeColor:@lightBlue; #header{ .wrapper(); width:@defaultWidth; height:80px; margin-bottom:20px; background:@defaultThemeColor; } #menu{ background:@defaultThemeColor; } 

而html如下:

  

当点击theme1时,应加载@lightRed主题,对于theme2 @lightBlue和对于theme3 @lightGreen

请让我知道我的javascript / jquery如何在点击时更改主题颜色

你可以尝试使用less.js函数,如:

 less.refreshStyles() 

要么

 less.modifyVars() 

你可以在这里阅读更多内容: 动态改变较少的变量

.click事件上使用jQuerymodifyVars这一行可能有效:

 $('.theme_option').click(function(event){ event.preventDefault(); less.modifyVars({ '@defaultThemeColor': $(this).attr('data-theme') }); }); 

使用单击事件更改背景颜色

这是使用on change更改背景颜色的示例..请查看[示例] [http://jsfiddle.net/6YVes/]

如果您只想更改背景颜色onclick li’s,请为每个li分配一个类并在每个类上触发jQuery click事件,如下所示:

HTML:

  

JS:

 $('.red').click(function(){ $(this).css('background-color',"red") }); $('.green').click(function(){ $(this).css('background-color',"red") }); $('.blue').click(function(){ $(this).css('background-color',"blue") }); 

请注意,lesscss是必须是compilerd的Css。 这意味着你不能直接修改你的lesscss的行为,但你可以编译css。 浏览器不明白你必须记住它。

所以,我认为最好的方法是在你想要修改的对象上使用两个类,一个用于形状,另一个用于主题。 通过这种方式,您可以通过使用jQuery修改主题类来从一个切换到另一个。 想象一下:

lesscss:

 .theme-1 { //Here goes your theme colors } .theme-2 { //Here goes more theme colors and rules } #header { .wrapper(); width:@defaultWidth; height:80px; margin-bottom:20px; background:@defaultThemeColor; } 

而你的HTML:

    

希望能帮助到你。

如前所述,最好将一个类应用于每个主题

CSS:

 /* -- [ light blue theme (default) ] ---------- */ #header, #header.lightblue { background: #ddf; height: 80px; margin-bottom: 20px; width: 300px; } #menu, #menu.lightblue { background: #ddf; } /* -- [ light red theme ] ---------- */ #header.lightred { background: #fdd; height: 95px; margin-bottom: 10px; width: 400px; } #menu.lightred { background: #fdd; } /* -- [ light green theme ] ---------- */ #header.lightgreen { background: #dfd; height: 72px; margin-bottom: 15px; width: 290px; } #menu.lightgreen { background: #dfd; } 

这样,要更改每个主题,您只需更改容器对象的类。 假设容器对象是文档主体,然后将主体的类更改为所需的主题。

HTML:

  

JavaScript(jQuery):

 jQuery('a.theme_option').click(function(e){ e.preventDefault(); var theme_class = jQuery(this).attr('data-theme'); jQuery(body).attr('class', theme_class); } 

css中的变量现在是草稿!

http://www.w3.org/TR/css-variables/