下面一個案例使用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 < cookies.length; i++) { <BR>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>