下面一个案例使用js实现一个页面浮层效果,并且通过两种方法使用js读写cookie来实现用户关闭广告的显示状态;
读者可以将下面代码复制到一个html文件试试效果;html的pre标签未两种js实现的方式
<br>1.第一种:使用jQuery的cookie库 <br>例子就是现在正在使用的js,相关代码如下: <br>$(document).ready(function () { <br>var adCookie=$.cookie("docCookie"); <br>//如果本地没有cookie,将词条cookie写入本地 <br>if(adCookie!="adDocCookie"){ <br>$("#wapDocCookie").show(); <br>} <br>//如果本地存在词条cookie,不显示浮层 <br>if(adCookie=="adDocCookie"){ <br>$("#wapDocCookie").hide(); <br>} <br>//关闭广告,隐藏浮层 <br>$("#closeAd").click(function(){ <br>$("#wapDocCookie").hide(); <br>$.cookie("docCookie","adDocCookie",{expires:60}); <br>}); <br><br>}); <br>//jQuery cookie library <br>jQuery.cookie = function(name, value, options) { <br>if (typeof value != 'undefined') { // name and value given, set cookie <br>options = options || {}; <br>if (value === null) { <br>value = ''; <br>options.expires = -1; <br>} <br>var expires = ''; <br>if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { <br>var date; <br>if (typeof options.expires == 'number') { <br>date = new Date(); <br>date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); <br>} else { <br>date = options.expires; <br>} <br>expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE <br>} <br>var path = options.path ? '; path=' + (options.path) : ''; <br>var domain = options.domain ? '; domain=' + (options.domain) : ''; <br>var secure = options.secure ? '; secure' : ''; <br>document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); <br>} else { // only name given, get cookie <br>var cookieValue = null; <br>if (document.cookie && document.cookie != '') { <br>var cookies = document.cookie.split(';'); <br>for (var i = 0; i var cookie = jQuery.trim(cookies[i]); <br>// Does this cookie string begin with the name we want? <br>if (cookie.substring(0, name.length + 1) == (name + '=')) { <br>cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); <br>break; <br>} <br>} <br>} <br>return cookieValue; <br>} <br>}; <br>2.第二种:自己写一个js操作cookie的实例 <br>相关js如下: <br>$(document).ready(function() { <br><br>function writeCookie(name,value) <br>{ <br>var exp = new Date(); <br>exp.setTime(exp.getTime() + 7*24*60*60*1000); <br>document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); <br>} <br>//读取cookies <br>function readCookie(name) <br>{ <br>var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); <br>if(arr=document.cookie.match(reg)){ <br>return unescape(arr[2]); <br>}else { <br>return null; <br>} <br>} <br>var adCookie = readCookie("adCookie"); <br><br>if(adCookie!="adDocCookie"){ <br>$("#wapDocCookie").show(); <br>} <br>//如果本地存在词条cookie,不显示浮层 <br>if(adCookie=="adDocCookie"){ <br>$("#wapDocCookie").hide(); <br>} <br><br>//关闭广告,隐藏浮层 <br>$("#closeAd").click(function(){ <br>$("#wapDocCookie").hide(); <br>}); <br>}); <br>