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
2 Answers
Reset to default 6While 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
版权声明:本文标题:Can javascript make a custom @rule of css? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745362115a2655342.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论