我正在做一个项目,我想在其中更改主题颜色,基于国家/地区的图标。例如,澳大利亚人很好地输入主题颜色:红色所以所有图标,文本或背景颜色都应该变为红色。
更改/加载不同的CSS是一个选项,但是,我希望用户将输入颜色,该颜色应传递给CSS文件,主题将更改。
有没有办法让我在CSS文件中传递用户输入的输入颜色代码?
使用vanilla 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>
不,除非您通过接受带颜色的查询参数的控制器生成CSS文件服务器端。
你可以创建一个select标签,它有值的选项,例如:
<select>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
https://www.youtube.com/watch?v=k2qJ8QbGbAU
这是一个视频,可以帮助你清楚地看到我的意思。
最好替换或添加页面主体的css类或id,以便您可以轻松更改该页面的每种样式。您可以使用jquery点击功能。例如:当你点击澳大利亚时,只需在body上使用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;
}
通过这种方式,您可以更改整个页面的颜色和主题。