首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过主题设置改变主题的颜色

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

Stack Overflow用户
提问于 2018-09-10 01:14:28
回答 4查看 148关注 0票数 0

我正在做一个项目,其中我想改变的主题颜色,图标的国家为基础。例如,澳大利亚人很好地输入了主题颜色:红色,所以所有的图标,以及文本或背景颜色都应该改为红色。

改变/加载不同的CSS是一种选择,但我希望用户将输入颜色,该颜色应传递到CSS文件和主题将发生变化。

有没有什么方法可以让我在CSS文件中传递用户输入的颜色代码?

EN

回答 4

Stack Overflow用户

发布于 2018-09-10 03:38:47

使用普通的JavaScript和CSS变量:

代码语言:javascript
复制
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();
代码语言:javascript
复制
/* 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;
}
代码语言:javascript
复制
<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
EN

Stack Overflow用户

发布于 2018-09-10 01:17:57

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

票数 0
EN

Stack Overflow用户

发布于 2018-09-10 01:23:24

您可以创建一个select标记,它的选项具有值,例如:

代码语言:javascript
复制
    <select>
        <option value="red">Red</option>
        <option value="blue">Blue</option>

</select>

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52246880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档