这里演示利用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视频教程!
