作者:mobiledu2502892903 | 来源:互联网 | 2018-06-23 00:25
下面一个案例使用js实现一个页面浮层效果,并且通过两种方法使用js读写COOKIE来实现用户关闭广告的显示状态;
读者可以将下面代码复制到一个html文件试试效果;html的pre标签未两种js实现的方式
代码如下:
本文作者:IT_Blog_杨凯
转载请指明出处:http://blog.csdn.net/yangkai_hudong
1.第一种:使用jQuery的COOKIE库
例子就是现在正在使用的js,相关代码如下:
$(document).ready(function () {
var adCOOKIE=$.COOKIE("docCOOKIE");
//如果本地没有COOKIE,将词条COOKIE写入本地
if(adCOOKIE!="adDocCOOKIE"){
$("#wapDocCOOKIE").show();
}
//如果本地存在词条COOKIE,不显示浮层
if(adCOOKIE=="adDocCOOKIE"){
$("#wapDocCOOKIE").hide();
}
//关闭广告,隐藏浮层
$("#closeAd").click(function(){
$("#wapDocCOOKIE").hide();
$.COOKIE("docCOOKIE","adDocCOOKIE",{expires:60});
});
});
//jQuery COOKIE library
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(); // use expires attribute, max-age is not supported by IE
}
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 { // only name given, get COOKIE
var COOKIEValue = null;
if (document.COOKIE && document.COOKIE != '') {
var COOKIEs = document.COOKIE.split(';');
for (var i = 0; i var COOKIE = jQuery.trim(COOKIEs[i]);
// Does this COOKIE string begin with the name we want?
if (COOKIE.substring(0, name.length + 1) == (name + '=')) {
COOKIEValue = decodeURIComponent(COOKIE.substring(name.length + 1));
break;
}
}
}
return COOKIEValue;
}
};
2.第二种:自己写一个js操作COOKIE的实例
相关js如下:
$(document).ready(function() {
function writeCOOKIE(name,value)
{
var exp = new Date();
exp.setTime(exp.getTime() + 7*24*60*60*1000);
document.COOKIE = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
//读取COOKIEs
function readCOOKIE(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.COOKIE.match(reg)){
return unescape(arr[2]);
}else {
return null;
}
}
var adCOOKIE = readCOOKIE("adCOOKIE");
if(adCOOKIE!="adDocCOOKIE"){
$("#wapDocCOOKIE").show();
}
//如果本地存在词条COOKIE,不显示浮层
if(adCOOKIE=="adDocCOOKIE"){
$("#wapDocCOOKIE").hide();
}
//关闭广告,隐藏浮层
$("#closeAd").click(function(){
$("#wapDocCOOKIE").hide();
});
});
点击下载