Two ways to dynamically create css in JS
There are two ways to dynamically create CSS styles:
1. Introducing external css files
2. Inserting css code snippets
Dynamically inserting css external files:
- 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' );
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
Dynamically load css snippets
- 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}' );
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
In IE, a tag is regarded as a special tag and cannot access its child elements, so use stylesheet .cssText and use try catch statement to catch errors thrown by IE. The compatible code is as follows:
- 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}' );
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15