开发者

how to: dynamically switch css page

开发者 https://www.devze.com 2023-03-08 10:00 出处:网络
I am working on a webpage for an embedded device where the server storage space is very limited. I want the user to be 开发者_Python百科able to switch between day mode and night mode viewing of the we

I am working on a webpage for an embedded device where the server storage space is very limited. I want the user to be 开发者_Python百科able to switch between day mode and night mode viewing of the webpages. To do so I would like to just load the page using a different webpage with a button is clicked. I don't want to have two copies of every page because I don't have enough space. Is there a way to switch to a different css page or load the css dynamically somehow? I can only use html and javascript. No PHP or asp.net.


Let me argue for something even simpler:

1: One CSS:

.day {
  color: black;
  background-color: white;
}

.night {
  color: white;
  background-color: black;
}

.day #content {
  color: blue;
}

.night #content{
  color: red;
}

2: One HTML:

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="dayornight.css">
  </head>
  <body class="day">
    <div id="content">
        <a>Hello World!</a>
    </div>
  </body>
</html>

3: A small piece of JavaScript or jQuery code tied to the button that toggles the class on the body tag from day to night.

As you can see if you bring this example up in your browser, changing the class not only changes the CSS style of the body, it can also shift the contained items as well because their selectors match differently now.


Here you go in plain javascript:

JS:

function change_css(){
    var oLink = document.createElement("link") 
    oLink.href = "new_css.css"; //new css filename
    oLink.rel = "stylesheet"; 
    oLink.type = "text/css"; 
    document.body.appendChild(oLink);
}

HTML:

<button onclick="change_css()" value="css change"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消