Как я могу применить миксины CSS с родной JavaScript?


Если мой браузер имеет собственную реализацию из свойств CSS, то у меня должен быть какой-то Javascript API для манипулирования миксинами, как я мог бы сделать с переменными CSS:

document.body.style.setProperty('--some-property', 'value');

Я погуглил его, но, к сожалению, в большинстве случаев я натыкался на фреймворк css, который имеет какой-то хак, чтобы сделать CSS mixin с javascript, к сожалению, я не нашел документацию API об этом, кто-то знает, как это сделать?

Элемент HTMLElement.стиль - это CSSStyleDeclaration у чего есть API, но там я могу найти только метод setProperty, но не метод setMixin.

Прогресс:

Если я добавляю к атрибуту стиля @apply --some-mixin;, то mixin не применяется. Теперь я думаю, что я должен попробовать сделать пользовательский встроенный css и добавить в документ, но это все еще какой-то халтурный способ сделать это, и он также не работает.

Вот некоторые фрагменты для тестирования, но будьте бдительны вам нужно активные функции веб-платформы experiental в вашем браузере, чтобы увидеть миксин работает!

let container = document.getElementById('container');

for(var i = 1; i<=5; i++)
{
    let itemElement = document.createElement('DIV');
        itemElement.classList.add('item');
        itemElement.innerText = `Some added item#${i}!`;
        itemElement.style.color = `var(--item-${i}-color, blue)`;
  
    let style = itemElement.getAttribute('style');
      itemElement.setAttribute('style', `${style} @apply --item-${i};`);
  
    container.appendChild( itemElement );
}

if( true /* some sort of logic which are not important */ )
{
    container.style.setProperty('--item-2-color', 'green');
  
    // @todo add custom mixin to item#4 to be highlighted someway, and use Javascript API without this type of hacks:

    let style = container.getAttribute('style');
    container.setAttribute('style', `${style} --item-4: { margin: 10px 0; background-color: orange; color: yellow; };`);
    
}
:root {
    /* static css mixin */
    --paper-shadow: {
      box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14),
                  0 1px 5px 0 rgba(0, 0, 0, 0.12),
                  0 3px 1px -2px rgba(0, 0, 0, 0.2);
    };
}
  
body, #container {
  background: #eee; font-family: Arial, sans-serif;
}
  
h2 {
  text-align: center;
}

#container {
  padding: 30px;
  
  --item-3-color: red;

  /* initial css mixin from dinamic mixin */
  --item-3: {
    font-weight: bold;
  };
}

#container .item {
  background: #fff; padding: 20px 10px;
  font-size: 90%; text-align: center; letter-spacing: 1px;
  
  @apply --paper-shadow;
}
<h2>You need to activate #experimental-web-platform-features in your browser to see the mixin working!</h2>
<div id="container"></div>
1 2

1 ответ:

Я нашел халтурное решение, которое работает, но не является точным типом API решения, которое я хочу, но для тех, кто хочет быстро решить проблему, можно получить атрибут style и добавить mixin directley к элементу:

let element = document.querySelector('some-element');

/* IMPORTANT!
 * do something with element.style and/or add css-property
 * before you change the style attribute!
 */

// get the current custom styles
let style = element.getAttribute('style');

// apply css mixin to the element:
element.setAttribute('style', `${style} @apply --some-mixin;`);

// set css mixin to the element:
element.setAttribute('style', `${style} --some-mixin: { /*...*/ };`);