通过主题设置改变主题颜色

时间:2018-09-09 17:14:28

标签: javascript jquery html

我正在做一个项目,我想更改主题颜色,即基于国家/地区的图标。例如,澳大利亚人会很好地输入主题颜色:红色,因此所有图标以及文本或背景色都应更改为红色。

更改/加载不同的CSS是一种选择,但是,我希望用户输入颜色,并且该颜色应该传递给CSS文件,并且主题会改变。

我可以通过什么方式在CSS文件中传递用户输入的输入颜色代码?

4 个答案:

答案 0 :(得分:1)

使用原始的JavaScript和CSS变量:

function customThemeColors ()
{
  // Get the flags container
  const flags = document.querySelector( '.flags' );
  
  // Reference
  let current = null;  
  
  // Add a click event
  flags.addEventListener( 'click', () => {
    
    // Clicked target
    let target = event.target;
    
    // If target is not a button or if it is the last one clicked return
    if ( target.nodeName !== 'BUTTON' || target === current ) return;
    
    // Get the color from the button attribute
    let color = target.getAttribute( 'data-theme-color' );
    
    // Set the css variable on the whole document
    document.documentElement.style.setProperty( '--custom-theme-color', color );
    
    // Reference to the button clicked
    current = target;
    
  });
}

// Usage example
customThemeColors();
/* Using CSS variables */

.color
{
  color: var( --custom-theme-color );
}

.background-color
{
  background-color: var( --custom-theme-color );
}

/* Everything else is not important, it is only for demonstration */

body
{
  display: flex;
  flex-direction: column;
  align-items: center;
}

.flags,
.container
{
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  width: 400px;
  height: 50px;
}

button
{
  width: 75px;
  height: 25px;
}

.container > div
{
  height: 50px;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div>CSS variables example</div>

<div class="flags">
  <button data-theme-color="#00F">Brazil</button>
  <button data-theme-color="#0F0">Australia</button>
  <button data-theme-color="#F00">Canada</button>
</div>

<div class="container">
  <div class="color">Color</div>
  <div class="background-color">Background-color</div>
</div>

答案 1 :(得分:0)

否,除非您通过接受带有颜色的查询参数的控制器在服务器端生成CSS文件,否则不会这么做。

答案 2 :(得分:0)

您可以创建一个选择标签,其中包含带有值的选项,例如:

After previous

https://www.youtube.com/watch?v=k2qJ8QbGbAU

这里有一段视频,可以帮助您清楚地理解我的意思。

答案 3 :(得分:0)

最好替换或添加页面正文的css类或id,以便您可以轻松更改该页面的每种样式。您可以使用jquery点击功能。例如:当您单击Australia时,只需在主体上使用addClass()函数并添加红色类。您还需要为该红色主题编写css。

示例:

$(document).ready(function(){
    $('.australia').on('click', function(){
      ('body').addClass('red');
    })
})

如有必要,您还可以在单​​击另一个班级的同时删除以前添加的班级。有关更多的jQuery函数,您可以遵循https://api.jquery.com

您还需要为上述红色类添加CSS,例如:

body.red {
 background-color: #FF0000;
}
body.red p,
body.red span,
body.red h1,
body.red i {
 background-color: #FF0000;
}

通过这种方式,您可以更改整个页面的颜色和主题。

相关问题