http://danielfarias.net

Trocando o CSS

  • 2009-08-18
  • Demonstrarei neste artigo como criar um menu que permita o usuário a escolher o layout do site. O funcionamento é simples. Criaremos um menu, neste caso, com dois links. Onde cada um “aponta” para uma folha de estilo diferente. Assim, quando o usuário clicar sobre o link ele escolherá qual folha de estilo usar e, consequentemente, o layout que mais lhe agrada. Para isso combinaremos três tipos de arquivo: HTML, CSS e JavaScript. Digite o código JavaScript abaixo crie a pasta “script” e salve-o com o nome styleswitcher.js nesta pasta.

     

    function setActiveStyleSheet(title) {
      var i, a, main;
      for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
        if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
          a.disabled = true;
          if(a.getAttribute("title") == title) a.disabled = false;
        }
      }
    }
    
    function getActiveStyleSheet() {
      var i, a;
      for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
        if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")
         && !a.disabled) return a.getAttribute("title");
      }
      return null;
    }
    
    function getPreferredStyleSheet() {
      var i, a;
      for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
        if(a.getAttribute("rel").indexOf("style") != -1
           && a.getAttribute("rel").indexOf("alt") == -1
           && a.getAttribute("title")
           ) return a.getAttribute("title");
      }
      return null;
    }
    
    function createCookie(name,value,days) {
      if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
      }
      else expires = "";
      document.cookie = name+"="+value+expires+"; path=/";
    }
    
    function readCookie(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
    }
    
    window.onload = function(e) {
      var cookie = readCookie("style");
      var title = cookie ? cookie : getPreferredStyleSheet();
      setActiveStyleSheet(title);
    }
    
    window.onunload = function(e) {
      var title = getActiveStyleSheet();
      createCookie("style", title, 365);
    }
    
    var cookie = readCookie("style");
    var title = cookie ? cookie : getPreferredStyleSheet();
    setActiveStyleSheet(title);
    
    

    Neste artigo não me atentarei a explicação do código JavaScript. Com o código JavaScript concluído, vamos escrever o HTML.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Trocando a folha de estilo
    <link rel="stylesheet" type="text/css" href="css/amarelo.css" media="all"  />
    <link rel="stylesheet" type="text/css" href="css/amarelo.css" title="default" media="all"  />
    <link rel="stylesheet" type="text/css" href="css/vermelho.css" title="vermelho" media="all"  />
    <script type="text/javascript" src="scripts/styleswitcher.js"></script>
    </head>
    <body>
    <h1>Trocando a folha de estilo
    
    <ul>
    <li><a href="#" onclick="setActiveStyleSheet('default'); return false;">Estilo padrão
    <li><a href="#" onclick="setActiveStyleSheet('vermelho'); return false;">Mudando o estilo
    </ul>
    

    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    <p>Exemplo criado por Daniel Farias.</p>

    </body>
    </html>
    
    

    Salve o arquivo com o nome trocandoestilos.html.
    A linha <link rel="stylesheet" type="text/css" href="css/amarelo.css" media="all" /> define qual será o arquivo CSS que será carregado como padrão do site.
    A linha <link rel="stylesheet" type="text/css" href="css/amarelo.css" title="default" media="all" /> passa o valor "default" através do atributo title.
    A linha <link rel="stylesheet" type="text/css" href="css/vermelho.css" title="vermelho" media="all" /> passa o valor "vermelho" através do atributo title.
    A linha <script type="text/javascript" src="scripts/styleswitcher.js"></script> faz o link com o arquivo styleswitcher.js.

    Crie agora dois arquivos CSS. Comece pelo amarelo.css.

    @charset "utf-8";
    /* CSS Document */
    /* Criado por Daniel Farias */
    
    *{
        font-family:"Times New Roman", Times, serif;
        color:#900;
        width:500px;
        height:auto;
        margin:0 auto;
    
    }
    
    body{
        background:#FFC;
        border: 1px #900 solid;
        margin:20px 0 0 0;
        padding:30px;
    }
    
    h1{
        margin:0 0 30px 0;
    }
    
    ul{
        margin:0;
        padding:0;
        list-style:none;
    }
    
    li a{
        display:block;
        width:200px;
        height:auto;
        padding:10px;
        background:#900;
        color:#FF9;
        float:left;
        margin:0px 10px 30px 10px;
        text-align:center;
    }
    
    p{
        text-align:justify;
        margin-bottom:10px;
    }
    E em seguida o arquivo vermelho.css.
    @charset "utf-8";
    /* CSS Document */
    /* Criado por Daniel Farias */
    *{
        font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
        color:#FFC;
        width:500px;
        height:auto;
        margin:0 auto;
    
    }
    
    body{
        background:#900;
        border: 1px #FFC solid;
        margin:20px 0 0 0;
        padding:30px;
    }
    
    h1{
        margin:0 0 30px 0;
    }
    
    ul{
        margin:0;
        padding:0;
        list-style:none;
    }
    
    li a{
        display:block;
        width:200px;
        height:auto;
        padding:10px;
        background:#FFC;
        color:#900;
        float:left;
        margin:0px 10px 30px 10px;
        text-align:center;
    }
    

    As diferenças entre os arquivos amarelo.css e vermelho.css são as cores do background e das fontes e o estilo das fontes. Não esqueça de salvar os dois arquivos CSS na pasta css e o arquivo HTML fora das pastas para que os links entre eles fiquem corretos.

    Agora você poderá “brincar” à vontade com as formatações CSS e criar estilos bem diferentes para um mesmo site. Isso o deixa mais dinâmico e atrativo ao usuário.

    Nos “veremos” na próxima. Tchau!

    Veja o exemplo.

  • 2010-05-14
  • Raissa Lopes
  • Gostaria de um exemplo assim que trocasse a imagem do fundo do palco do site, como o que é possível de fazer no twitter. Obrigada pela atenção.
  • 2010-05-11
  • dzYgltHDyLhkSdN
  • ub9XRt hynperpylwmp, [url=http://wgryunjgpodw.com/]wgryunjgpodw[/url], [link=http://udttoitxqnil.com/]udttoitxqnil[/link], http://xglkqsrggstb.com/