admin管理员组

文章数量:1422330

CSS have rules like @media, @keyframes, etc. Can such be made using javascript, e.g. @myCustomRule. If yes then how ? If no then is there any alternative to that or just to go with CSS ?

CSS have rules like @media, @keyframes, etc. Can such be made using javascript, e.g. @myCustomRule. If yes then how ? If no then is there any alternative to that or just to go with CSS ?

Share Improve this question asked Oct 21, 2019 at 14:40 debarchitodebarchito 1,3351 gold badge9 silver badges22 bronze badges 4
  • 2 What are you trying to achieve? – Turnip Commented Oct 21, 2019 at 14:43
  • 3 Those are called "at-rules". No, you cannot make custom at-rules in JS. developer.mozilla/en-US/docs/Web/CSS/At-rule – user47589 Commented Oct 21, 2019 at 14:43
  • You'd have to make your own pre-processor/pre-processing function that parses your stylesheet for your custom rule at pile time. The easiest way would be to create a webpack loader, or a function for whatever task runner you're using (if you're using one). When parsing, you'd have to replace your custom rule with native CSS that the browser can read. – Jay Kariesch Commented Oct 21, 2019 at 14:50
  • Thats a great idea – debarchito Commented Oct 21, 2019 at 16:09
Add a ment  | 

2 Answers 2

Reset to default 6

While you can't create your own custom @rules, you can use the CSSOM to create supported rules and insert them into one of the browser's stylehseets with JavaScript:

button.addEventListener('click', function () {
  const sheets = document.styleSheets;
  const lastStyleSheet = sheets[sheets.length - 1];
  const rule = `@keyframes rotate {
                  0%  {
                    transform: rotate(0deg);
                  } 100% {
                    transform: rotate(360deg);
                  }
                }`;

  lastStyleSheet.insertRule(rule, lastStyleSheet.rules.length);
  box.classList.add('rotate');
});
#box {
  border: 1px solid black;
  height: 50px;
  width: 50px;
}

#box.rotate {
  animation: rotate 100ms infinite;
}
<div id="box"></div>
<button id="button">Add Animation via JS</button>

It turned out that there is a way, well explained here:

Defining Custom At-Rules in CSS

it uses jsincss and jsincss-element-query

本文标签: Can javascript make a custom rule of cssStack Overflow