W3C.US

  • Increase font size
  • Default font size
  • Decrease font size
Home Experience Javascript How to change the loaded page's CSS?

How to change the loaded page's CSS?

E-mail Print PDF

Some sites should provide the function let the user to change their pages appearance. When the user click the favorite template, the page has no reload, but change to the specific style.

To do this, single line Javascript code is enough:

document.styleSheets(i).href="/new.css";

The variable i indicates the stylesheet link index in the html source. Most simple pages only have one stylesheet, so i should be 0.

For example, the html file(test.html) content:

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test change CSS</title>
<link href="/old.css" rel="stylesheet" type="text/css" />
<script language="javascript">
function changeStyle() {
    document.styleSheets(0).href="/new.css";
}
</script>
</head>

<body>
<h1>This title's style is for change</h1>
<input type="button" value="Change Style" onclick="changeStyle()">
</body>
</html>

 

 And the old styleSheet file(old.css):

/* CSS Document */

h1{
color:#0000CC
}

The new styleSheet file(new.css):

/* CSS Document */

h1{
color:#00DDCC
}

After loaded, the page:

After clicked the "Change Style" button:

The pages styleSheet file change to new.css.

The upper code works well in Internet Explorer, but in Firefox or other W3C browser, directly set the value of document.styleSheets(0).href doesn't work.

Because in W3C, it is only a read-only property, not writable.

We can change the javascript code to handle it.

1.Give an id to the externel stylesheet link:

<link href="/old.css" rel="stylesheet" type="text/css" /> => <link href="/old.css" rel="stylesheet" type="text/css" id="outercss" />

2.Use document.getElementById to get the stylesheet link:

function changeStyle() {

var csslink = document.getElementById("outercss");
csslink.href = "new.css";

}

Then the code can work on IE and Firefox properly.

Last Updated on Thursday, 30 April 2009 01:56