我正在做一个项目,其中我想改变的主题颜色,图标的国家为基础。例如,澳大利亚人很好地输入了主题颜色:红色,所以所有的图标,以及文本或背景颜色都应该改为红色。
改变/加载不同的CSS是一种选择,但我希望用户将输入颜色,该颜色应传递到CSS文件和主题将发生变化。
有没有什么方法可以让我在CSS文件中传递用户输入的颜色代码?
发布于 2018-09-10 03:38:47
使用普通的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>
发布于 2018-09-10 01:17:57
不,除非您通过接受带有颜色的查询参数的控制器在服务器端生成CSS文件。
发布于 2018-09-10 01:23:24
您可以创建一个select标记,它的选项具有值,例如:
<select>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>https://www.youtube.com/watch?v=k2qJ8QbGbAU
这里有一个视频,可以帮助你清楚地理解我的意思。
https://stackoverflow.com/questions/52246880
复制相似问题