Home > Web Front-end > JS Tutorial > body text

JavaScript inserts dynamic style implementation code_javascript skills

WBOY
Release: 2016-05-16 17:56:04
Original
1063 people have browsed it

Similar to dynamic scripts, the so-called dynamic styles refer to styles that do not exist when the page is first loaded; dynamic styles are dynamically added to the page after the page is loaded.

Let’s take the following typical element as an example:

This element can be easily created dynamically using DOM code:

Copy code The code is as follows:

var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = "style.css";
var head = document.getElementsByTagName("head")[0];
head.appendChild(link);

The above code can run normally in all major browsers. Note that the element must be added to the rather than the element to ensure consistent behavior across all browsers. The whole process can be represented by the following function:
Copy code 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")

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

Another way to define styles is to use the

Following the same logic, the following DOM code should be valid:
Copy code 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, but an error will be reported in IE. IE treats