Nat*_*teW 16 css postcss css-modules react-css-modules react-boilerplate
我正在使用一个(现在较旧的)版本的react-boilerplate,它带有CSS模块.它们的优点在于您可以创建变量并将其导入其他CSS文件中.
这是我的colors.css文件
:root {
/* Status colors */
--error: #842A2B;
--success: #657C59;
--pending: #666;
--warning: #7E6939;
}
Run Code Online (Sandbox Code Playgroud)
当我导入该文件时,我只需要在我的.css文件的顶部使用:
@import 'components/App/colors.css';
Run Code Online (Sandbox Code Playgroud)
我希望我的网站有两个主题的选项,我希望能够使用Javascript动态更新这些变量.最好的方法是什么?
编辑:我希望有一种方法来更新colors.css文件,而不必在从两个可能的css文件中提取的所有组件中进行条件导入...让我知道是否有办法做到这一点,如果有,我会改变接受的答案.谢谢所有回答的人!
Mic*_*ker 12
我只想在元素上使用默认的颜色变量/ body/然后将备用主题颜色放在另一个类中,并通过JS切换主题类.这是一个演示.
$("button").on("click", function() {
$("body").toggleClass("foo");
});Run Code Online (Sandbox Code Playgroud)
body {
--red: red;
--blue: blue;
--yellow: yellow;
background: #ccc;
text-align: center;
font-size: 5em;
}
.foo {
--red: #ce1126;
--blue: #68bfe5;
--yellow: #ffd100;
}
.red {
color: var(--red);
}
.blue {
color: var(--blue);
}
.yellow {
color: var(--yellow);
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="red">RED</span> <span class="blue">BLUE</span> <span class="yellow">YELLOW</span>
<br>
<button>click me</button>Run Code Online (Sandbox Code Playgroud)
小智 3
这是你想要的?
// get the inputs
const inputs = [].slice.call(document.querySelectorAll('.controls input'));
// listen for changes
inputs.forEach(input => input.addEventListener('change', handleUpdate));
inputs.forEach(input => input.addEventListener('mousemove', handleUpdate));
function handleUpdate(e) {
// append 'px' to the end of spacing and blur variables
const suffix = (this.id === 'base' ? '' : 'px');
document.documentElement.style.setProperty(`--${this.id}`, this.value + suffix);
}Run Code Online (Sandbox Code Playgroud)
:root {
--base: #ffc600;
--spacing: 10px;
--blur: 10px;
}
body {
text-align: center;
}
img {
padding: var(--spacing);
background: var(--base);
-webkit-filter: blur(var(--blur));
/* */
filter: blur(var(--blur));
}
.hl {
color: var(--base);
}
/*
misc styles, nothing to do with CSS variables
*/
body {
background: #193549;
color: white;
font-family: 'helvetica neue', sans-serif;
font-weight: 100;
font-size: 50px;
}
.controls {
margin-bottom: 50px;
}
a {
color: var(--base);
text-decoration: none;
}
input {
width:100px;
}Run Code Online (Sandbox Code Playgroud)
<h2>Update CSS Variables with <span class='hl'>JS</span></h2>
<div class="controls">
<label>Spacing:</label>
<input type="range" id="spacing" min="10" max="200" value="10">
<label>Blur:</label>
<input type="range" id="blur" min="0" max="25" value="10">
<label>Base Color</label>
<input type="color" id="base" value="#ffc600">
</div>
<img src="http://unsplash.it/800/500?image=899">
<p class="love"></p>
<p class="love">Chrome 49+, Firefox 31+</p>Run Code Online (Sandbox Code Playgroud)