CSS body class jquery切换器与cookie

时间:2014-03-25 00:12:37

标签: javascript jquery html css cookies

到目前为止,我正在使用一个背景切换器,它是根据我发现的一些示例和教程编写的,它包含一个样式表和一些子类,每个子类包含不同的背景图像;当单击切换器图像时,javascript按顺序依次切换下​​一个正文类,并将新值写入cookie。一切正常,除了在页面加载时加载cookie。如果我刷新页面,则cookie不会回忆,因此body类不会默认为最后选择的类。这是代码

以下是jsfiddle:http://jsfiddle.net/Lse3V/2/

的index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"><head> 
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="description" content="background switcha" /> 
        <meta name="keywords" content="" /> 
        <title>background switcha</title>
        <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
    <script type="text/javascript" src="head.js"></script>
    <script type="text/javascript">head.js( "jquery.js","back.js",  function() { });</script>
</head>
<body class="orig">
                <a href="javascript:void(0);" id="backgroundswap"></a>
</body>
</html>

的style.css

body.green{background: #3F0 url(background1.jpg) center top fixed repeat}
body.blue{background: #00F url(background2.jpg) center -80px fixed repeat}
body.red{background: #F00 url(background3.jpg) center top fixed repeat}
body.grey,html{background: #666 url(background4.jpg) repeat}
body{min-height:800px}
#backgroundswap{display:block;display:inline-block;zoom:1;width:101px;height:22px;background-image:url(backgroundswap.png);background-repeat:no-repeat;margin-bottom:12px;}
body.green #backgroundswap{background-position:center bottom}
body.blue #backgroundswap{background-position:0 -66px}
body.red #backgroundswap{background-position:0 -44px}
body.grey #backgroundswap{background-position:0 -22px}
body.orig{background-position:0 0}

body.orig{
background: #FF0 url(background5.jpg) center top fixed repeat
}

back.js

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }

        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { 
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);

                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function(){

    //Switch backgrounds and create the cookie...

    $("#backgroundswap").click(function(){

        var old_bg = ["green","blue","red","grey","orig"];

        var new_bg = ["blue","red","grey","orig","green"];

        var currentClass = $('body').attr("class");

            if(!Array.indexOf){ Array.prototype.indexOf = function(obj){ for(var i=0; i<this.length; i++){ if(this[i]===obj){ return i; } } return -1; } }

        $('body').removeClass().addClass(new_bg[old_bg.indexOf(currentClass)]);

        $.cookie('backswap', old_bg.indexOf($('body').attr("class")), { path: '/', expires: 365 });


    });

  });

head.js

 (function(a){var b=a.documentElement,c=navigator.userAgent.toLowerCase().indexOf("msie")!=-1,d=false,e=[],f={},g={},h=a.createElement("script").async===true||"MozAppearance"in a.documentElement.style||window.opera;var i=window.head_conf&&head_conf.head||"head",j=window[i]=window[i]||function(){j.ready.apply(null,arguments)};var k=0,l=1,m=2,n=3;h?j.js=function(){var a=arguments,b=a[a.length-1],c=[];r(b)||(b=null),q(a,function(d,e){d!=b&&(d=p(d),c.push(d),v(d,b&&e==a.length-2?function(){s(c)&&b()}:null))});return j}:j.js=function(){var a=arguments,b=[].slice.call(a,1),c=b[0];if(!d){e.push(function(){j.js.apply(null,a)});return j}c?(q(b,function(a){r(a)||u(p(a))}),v(p(a[0]),r(c)?c:function(){j.js.apply(null,b)})):v(p(a[0]));return j},j.ready=function(a,b){r(a)&&(b=a,a="ALL");var c=g[a];if(c&&c.state==n||a=="ALL"&&s()){b();return j}var d=f[a];d?d.push(b):d=f[a]=[b];return j};function o(a){var b=a.split("/"),c=b[b.length-1],d=c.indexOf("?");return d!=-1?c.substring(0,d):c}function p(a){var b;if(typeof a=="object")for(var c in a)a[c]&&(b={name:c,url:a[c]});else b={name:o(a),url:a};var d=g[b.name];if(d)return d;for(var e in g)if(g[e].url==b.url)return g[e];g[b.name]=b;return b}function q(a,b){if(a){typeof a=="object"&&(a=[].slice.call(a));for(var c=0;c<a.length;c++)b.call(a,a[c],c)}}function r(a){return Object.prototype.toString.call(a)=="[object Function]"}function s(a){a=a||g;for(var b in a)if(a[b].state!=n)return false;return true}function t(a){a.state=k,q(a.onpreload,function(a){a.call()})}function u(a,b){a.state||(a.state=l,a.onpreload=[],w({src:a.url,type:"cache"},function(){t(a)}))}function v(a,b){if(a.state==n&&b)return b();if(a.state==m)return j.ready(a.name,b);if(a.state==l)return a.onpreload.push(function(){v(a,b)});a.state=m,w(a.url,function(){a.state=n,b&&b(),q(f[a.name],function(a){a()}),s()&&q(f.ALL,function(a){a.done||a(),a.done=true})})}function w(c,d){var e=a.createElement("script");e.type="text/"+(c.type||"javascript"),e.src=c.src||c,e.async=false,e.onreadystatechange=e.onload=function(){var a=e.readyState;!d.done&&(!a||/loaded|complete/.test(a))&&(d(),d.done=true)},b.appendChild(e)}setTimeout(function(){d=true,q(e,function(a){a()})},300),!a.readyState&&a.addEventListener&&(a.readyState="loading",a.addEventListener("DOMContentLoaded",handler=function(){a.removeEventListener("DOMContentLoaded",handler,false),a.readyState="complete"},false))})(document)

1 个答案:

答案 0 :(得分:0)

您正在设置Cookie很棒,但如果确实检测到它,则无需检查它是否设置或操作。这段代码将为你做这个。

if($.cookie('backswap')) {

    $('body').removeClass().addClass(old_bg[$.cookie('backswap')]);

};

还有一些其他微小的调整,以确保数组的范围适用于所有内容,因此这里有一大堆代码受到影响。

$(document).ready(function(){

    window.new_bg = ["blue","red","grey","orig","green"]; 
    window.old_bg = ["green","blue","red","grey","orig"];

    if($.cookie('backswap')) {

        $('body').removeClass().addClass(old_bg[$.cookie('backswap')]);

    };


    //Switch backgrounds and create the cookie...

    $("#backgroundswap").click(function(){

        currentClass = $('body').attr("class");

        $('body').removeClass().addClass(new_bg[old_bg.indexOf(currentClass)]);

        $.cookie('backswap', old_bg.indexOf($('body').attr("class")), { path: '/', expires: 365 });

    });

});

希望这有帮助!