there are two ways to dynamically create CSS styles:
1. Introduce external CSS files
2. Insert CSS snippet
how to insert CSS external files dynamically:
function loadStyle(url){
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
var head = document.getElementsByTagName('head')[0];
head.appendChild(link);
}
loadStyle('test.css');
dynamically loads CSS snippet
function loadCssCode(code){
var style = document.createElement('style');
style.type = 'text/css';
style.rel = 'stylesheet';
//for Chrome Firefox Opera Safari
style.appendChild(document.createTextNode(code));
//for IE
//style.styleSheet.cssText = code;
var head = document.getElementsByTagName('head')[0];
head.appendChild(style);
}
loadCssCode('body{background-color:#f00}');
IE & lt; link> The tag is considered a special tag and its children cannot be accessed, so stylesheet.csstext is used, and errors thrown by IE are caught using a try catch statement, with the following compatible code:
function loadCssCode(code){
var style = document.createElement('style');
style.type = 'text/css';
style.rel = 'stylesheet';
try{
//for Chrome Firefox Opera Safari
style .appendChild(document.createTextNode(code));
}catch(ex){
//for IE
style.styleSheet.cssText = code;
}
var head = document.getElementsByTagName('head')[0];
head.appendChild(style);
}
loadCssCode('body{background-color:#f00}');
adds styles to the page in real time, so you can react instantly on the page.
Read More:
- A method of collecting JS dynamic content by PHP
- CSS: several ways to center the box vertically and horizontally
- Invalidation of margin top property of nested box in CSS style box
- Error: can’t resolve ‘FS’ in (webpack 2 configures CSS loaders)
- ERROR in ./node_modules/css-loader/dist/cjs.js!./node_modules/less-loader/dist/cjs.js!./src/css/spec
- When using CSS to write the registration page, we found that the editing effect is not effective
- On the dynamic acquisition of expandedheight of sliderappbar in nestedscrollview
- Error reporting under layui dynamic select IE
- Practice — CSS3 — frame animation to achieve special effects
- error: expected unqualified-id before ‘dynamic_cast’
- CSS remove the blue box after button click
- Free dynamic screen capture drawing tool under MAC: KAP
- error while loading shared libraries: requires glibc 2.5 or later dynamic linker
- JS error: permission denied to access property ‘document’— document.domain -The same source strategy of JavaScript
- CSS Failed to decode downloaded font, OTS parsing error: Failed to convert WOFF 2.0 font to SFNT
- Syntax Error: SassError: Invalid CSS after “…-height: #{math“: expected expression (e.g. 1px, bold
- ImportError: dynamic module does not define module export function (PyInit_cv_bridge_boost)
- ERROR: Adobe Flashplayer or HTML5 Browser with WebGL or CSS3D support requ
- Windows10解决ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed