原生JS关于cookie 的操作

公司业务需要,需要频繁地对cookie操作,遂完成代码封装,方便 团队小伙伴儿 一起使用

/*
* COOKIE 的 通用方法
* @name:  cookieName
* @value:  cookieValue
* @days:   几天 大于0,建议为整数
* @isZero: 是否是零点
*/
window.SpCusCookie = {
    setCookie: function (name, value, days, isZero) {
        var date = new Date(),
            expires = "",
            days = Number(days);
        if (days) {
            if(isZero) {
                var curTemp = date.getTime();
                var curWeekHours = new Date(date.toLocaleDateString()).getTime() - 1;
                var passedTimeStamp = curTemp - curWeekHours;
                var leftTimeStamp = 24 * 60 * 60 * 1000 - passedTimeStamp;
                var leftTime = new Date();
                leftTime.setTime(leftTimeStamp + curTemp + (days-1) * 24 * 60 * 60 * 1000);
                expires = "; expires="+leftTime.toGMTString();
            } else {
                date.setTime(date.getTime()+(days*24*60*60*1000));
                expires = "; expires="+date.toGMTString();
            }
        }
        document.cookie = name+"="+value+expires+"; path=/";
    },
    getCookie: function (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;
    },
    deleteCookie: function (name) {
        var date = new Date();
        date.setTime(date.getTime()-10000); //删除一个cookie,就是将其过期时间设定为一个过去的时间
        document.cookie = name + "= ' ' " + "; expires=" + date.toUTCString()+";path="+"/";
    }
}

因为公司内部使用(.699pic.com),所以代码均不涉及跨域,如果涉及跨域建议传默认参数 domain

你可能感兴趣的:(javascript,cookie,封装)