這篇文章主要介紹了JS利用cookie記憶目前位置的防刷新導航效果,涉及JavaScript操作cookie及導航樣式佈局的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下,具體如下:
這裡示範利用cookie記憶目前位置的防刷新導航條,主要向大家展示如何在Js中使用Cookies技術,用好了Cookies,會讓你的Js技術更上一層樓。這個選單感覺不錯,當你滑鼠點擊之後,重新刷新頁面後它仍然是保留在原始位置,好像帶有記憶功能。
運作效果截圖如下:
線上簡報網址如下:
http://demo.jb51.net/ js/2015/js-cookie-nav-pos-menu-demo/
具體程式碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>cookie记忆-防刷新菜单</title> <style> a{color:#5A73F3;text-decoration:none} body{background:#333;margin:30px;font-size:14px;} #menu li{float:left;height:25px;line-height:25px;list-style:none} #menu li a{padding:10px;} a:hover{background:#ccc;color:##3399FF} a.hover{height:25px;line-height:25px;background:red;color:#ffffff} a,area{blr:e-xpression(this.onFocus=this.blur())} :focus{-moz-outline-style:none;} </style> </head> <body> <p id="menu"> <ul> <li><a href="javascript:void(0)" class="hover" onclick="changename(0)" hidefocus="true">我的菜单</a></li> <li><a href="javascript:void(0)" onclick="changename(1)" hidefocus="true">网页模板</a></li> <li><a href="javascript:void(0)" onclick="changename(2)" hidefocus="true">精品代码</a></li> <li><a href="javascript:void(0)" onclick="changename(3)" hidefocus="true">设计素材</a></li> <li><a href="javascript:clear();" hidefocus="true">恢复初始</a></li> </ul> </p> <script language="javascript"> function changename(c,cl) { var d=document.getElementById("menu").getElementsByTagName("a"); if(!cl) { writeCookie("hovers",c,222); } c=readCookie("hovers")?readCookie("hovers"):c; for(i=0;i<d.length;i++) { d[i].className=i==c?"hover":""; } } function writeCookie(name, value, hours) { var expire = ""; if(hours != null) { expire = new Date((new Date()).getTime() + hours * 3600000); expire = "; expires=" + expire.toGMTString(); } document.cookie = name + "=" + escape(value) + expire; } function readCookie(name) { var cookieValue = ""; var search = name + "="; if(document.cookie.length > 0) { offset = document.cookie.indexOf(search); if (offset != -1) { offset += search.length; end = document.cookie.indexOf(";", offset); if (end == -1) end = document.cookie.length; cookieValue = unescape(document.cookie.substring(offset, end)) } } return cookieValue; } function clear() { writeCookie("hovers","",222); document.location=document.location.href; } changename(0,1) </script> </body> </html>
以上就是本章的全部內容,更多相關教學請訪問JavaScript視訊教學!