Today I have studied how JS uses the setattribute method to implement two style sheets on a page. The specific method is as follows:
Step 1: Define an ID in the element connecting to the style sheet, for example
CopyCode The Code is as follows: <link href1_1_1.css "rel =" stylesheet "type =" text/CSS "id =" CSS ">
The id I define is CSS.
Step 2: Write a JS function with the following code:Copy codeThe Code is as follows: <SCRIPT type = "text/JavaScript">
Function Change (){
VaR CSS = Document. getelementbyid ("CSS ");
If (A = 1)
Css.setattribute(“href”, ”1.css ");
If (A = 2)
Css.setattribute(“href”, ”2.css ");
}
</SCRIPT>
The code of this function can be stored anywhere on the page.
Step 3: Add a function trigger event to change the style sheet connection. The Code is as follows:Copy codeThe Code is as follows: <a href = "#" onclick = "Change (1)"> 1.css</A>
<A href = "#" onclick = "Change (2)"> 2.css</A>
This effect has been tested in IE and ff. I believe it is very clear after reading it. With this method, we can allow the viewer to select the style sheet to be displayed, for example, you can select a style sheet with a large font. Note the following two points:
In this example, the name of a function cannot be links or link. If it is links or link, the style sheet will not be changed. I am not sure about the specific reason, it may be a reserved character of JavaScript.
In addition, to change the style of the entire page, you need to define the height of the body as 100% in the style sheet file.
Method 2:
Step 1: import two sets of CSS filesCopy codeThe Code is as follows: <LINK rel = "stylesheet" type = "text/CSS" Title = "style a" href = "CSS/lele1.css"/>
<LINK rel = "alternate stylesheet" type = "text/CSS" Title = "style B" href = "CSS/lele2.css"/>
Step 2: Write the JS function for switchingCopy codeThe Code is as follows: <SCRIPT type = "text/JavaScript">
VaR Title = "style ";
Function setstyle (){
// Only switch between style a and style B
If (Title = "style "){
Title = "style B ";
} Else {
Title = "style ";
}
VaR I, links;
// Use the DOM method to retrieve all link elements
Links = Document. getelementsbytagname ("Link ");
// Determine whether each link element contains a style string to determine whether the link element is a style table link and whether the Link contains the title attribute.
For (I = 0; Links [I]; I ++ ){
If (Links [I]. getattribute ("rel"). indexof ("style ")! =-1 & Links [I]. getattribute ("title ")){
// Set all links to Disabled
Links [I]. Disabled = true;
// Determine whether a specified title string exists in the title. Set the current link to visible to activate the current link.
If (Links [I]. getattribute ("title"). indexof (title )! =-1 ){
Links [I]. Disabled = false;
// Alert ("OK ");
}
}
}
}
</SCRIPT>
Step 3: Call the switched JS function in the HTML tag copy Code the code is as follows: 1
2
3
4
5