Подтвердить что ты не робот

Обновление переменных модуля CSS из Javascript

Я использую (теперь более старую) версию реактивного шаблона, который поставляется с CSS-модулями. Что с ними приятно, так это то, что вы можете создавать переменные и импортировать их в другие файлы CSS.

Здесь мой файл colors.css

:root {
  /* Status colors */
  --error: #842A2B;
  --success: #657C59;
  --pending: #666;
  --warning: #7E6939;
}

Когда я импортирую этот файл, мне просто нужно использовать его в верхней части моего .css файла:

@import 'components/App/colors.css';

Я ищу вариант для двух тем для моего сайта, и я хотел бы иметь возможность динамически обновлять эти переменные с помощью Javascript. Какой лучший способ сделать это?

Изменить: я надеялся, что у вас есть способ обновить файл colors.css и не придется выполнять условный импорт во всех компонентах, которые извлекаются из двух возможных файлов css... дайте мне знать, есть ли способ сделать это и если есть, я изменю принятый ответ. Спасибо всем, кто ответил!

4b9b3361

Ответ 1

Я бы просто использовал цветные цвета по умолчанию для элемента / body/whatever, затем поместил альтернативные цвета тем в другой класс и переключил класс темы через JS. Вот демо.

$("button").on("click", function() {
  $("body").toggleClass("foo");
});
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);
}
<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>

Ответ 2

Это то, что вы ищете?

      // 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);
      }
: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;
}
<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>

Ответ 3

Я бы имел 2 листа и условно переключался между ними:

colours.scss

:root {
  /* Status colors */
  --error: #842A2B;
  --success: #657C59;
  --pending: #666;
  --warning: #7E6939;
}

otherColours.scss

:root {
  /* Status colors */
  --error: #FF0000;
  --success: #00FF00;
  --pending: #6666FF;
  --warning: #FF00FF;
}

то в вашем коде реакции импортируйте их и используйте их по своему усмотрению:

import styles from 'colours.scss';
import alternativeStyles from 'otherColours.scss';

...

{this.props.useNormalStyle ? styles.myClass : alternativeStyles.myClass}