xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub! how to create a style element in js (many ways)
create style in js
Constructed StyleSheets
CSSStyleSheet
adoptedStyleSheets
Shadow Roots (Shadow DOM)
Documents
demo
// Create our shared stylesheet:
const sheet = new CSSStyleSheet();
sheet.replaceSync('a { color: red; }');
// Apply the stylesheet to a document:
document.adoptedStyleSheets = [sheet];
// Apply the stylesheet to a Shadow Root:
const node = document.createElement('div');
const shadow = node.attachShadow({ mode: 'open' });
shadow.adoptedStyleSheets = [sheet];
https://developers.google.com/web/updates/2019/02/constructable-stylesheets
insertAdjacentHTML
document.head.insertAdjacentHTML("beforeend", `<style>body{background:red}</style>`)
styleSheet.cssText
const styleNode = document.createElement('style');
styleNode.type = "text/css";
// browser detection (based on prototype.js)
if(!!(window.attachEvent && !window.opera)) {
styleNode.styleSheet.cssText = 'span { color: rgb(255, 0, 0); }';
} else {
var styleText = document.createTextNode('span { color: rgb(255, 0, 0); } ');
styleNode.appendChild(styleText);
}
document.getElementsByTagName('head')[0].appendChild(styleNode);
innerHTML
const style = document.createElement('style');
style.innerHTML = `
#target {
color: blueviolet;
}
`;
document.head.appendChild(style);
style.sheet.insertRule
const style = document.createElement('style');
style.sheet.insertRule('#target {color: darkseagreen}');
document.head.appendChild(style);
CSSStyleSheet
// Create our shared stylesheet:
const sheet = new CSSStyleSheet();
sheet.replaceSync('#target {color: darkseagreen}');
// Apply the stylesheet to a document:
document.adoptedStyleSheets = [sheet];
https://dev.to/karataev/set-css-styles-with-javascript-3nl5
style
const div = document.createElement('div');
div.style.color = "red";
document.head.appendChild(style);
setAttribute
https://www.w3schools.com/JSREF/met_element_setattribute.asp
const div = document.createElement('div');
div.setAttribute(`style`, `color: red;`)
document.head.appendChild(style);
refs
style element & web components
https://www.cnblogs.com/xgqfrms/p/13614365.html
https://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript
https://www.w3schools.com/JSREF/prop_html_style.asp
https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript
https://www.geeksforgeeks.org/how-to-create-a-style-tag-using-javascript/
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!