JavaScript insert dynamic style implementation code _ javascript tips-js tutorial

Source: Internet
Author: User
The CSS style can contain two elements in the HTML page. The & lt; link & gt; element is used to contain files from external sources, while the & lt; style & gt; element is used to specify the embedded style similar to the dynamic script, A dynamic style is a style that does not exist when the page is loaded. A dynamic style is dynamically added to the page after the page is loaded.

The typical Element:

Using DOM code, you can easily dynamically create this element:

The Code is as follows:


Var link = document. createElement ("link ");
Link. rel = "stylesheet ";
Link. type = "text/css ";
Link. href = "style.css? 1.1.23 ";
Var head = document. getElementsByTagName ("head") [0];
Head. appendChild (link );


The above code can run normally in all mainstream browsers. Note that Add elementInsteadTo ensure the behavior consistency in all browsers. The entire process can be represented by the following functions:

The Code is as follows:


Function loadStyles (url ){
Var link = document. createElement ("link ");
Link. rel = "stylesheet ";
Link. type = "text/css ";
Link. href = url;
Var head = document. getElementsByTagName ("head") [0];
Head. appendChild (link );
}
LoadStyles ("style.css? 1.1.23 ")


The process of loading external style files is asynchronous, that is, there is no fixed order between the process of loading styles and executing JavaScript code.

Another way to define a style is to use

The following DOM code should be valid according to the same logic:

The Code is as follows:


Var style = document. createElement ("style ");
Style. type = "text/css ";
Style. appendChild (document. createTextNode ("body {background-color: red ;}"));
Var head = document. getElementsByTagName ("head") [0];
Head. appendChild (style );


The above code can be run in Firefox, Safrai, Chrome, and Opera, and an error will be reported in IE. IE will

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.