jQuery使用cookie展开/隐藏



我有以下代码。实际上,我需要一个cookie,即使用户重新加载页面,它也能记住div的当前状态。非常感谢你的帮助!

jQuery(function(){
jQuery(".menu i").hide();
jQuery("#showmenu").click(function(){
if(jQuery(".side-menu").width() > "87"){
jQuery(".side-menu").animate({width: '-=205px'});
jQuery(".main-section").animate({'margin-left': '-=205px'});
jQuery(".logo").text("2");
jQuery("span.text").hide();
jQuery(".menu i").show();
}
else {
jQuery(".side-menu").animate({width: '+=205px'});
jQuery(".main-section").animate({'margin-left': '+=205px'});
jQuery(".logo").text("1");
jQuery("span.text").show("slow");
jQuery(".menu i").hide();
}
});
});

这是div

<div class="wrapper">
<div class="side-menu">
<div class="logo">
Vi Dairy
</div>
<div class="menu">
<ul>
<li><a href="#"><i class="fa fa-home" style="font-size:15px;color:white;"></i><span class="text">test</span></a>
<ul class="dropdown">
<li><a href="#"><i class="fa fa-heart" style="font-size:15px;color:white;"></i><span class="text">test</span></a></li>
<li><a href="#"><i class="fa fa-history" style="font-size:15px;color:white;" aria-hidden="true"></i><span class="text"> test</span></a></li>
<li><a href="#"><i class="fa fa-thumbs-up" style="font-size:15px;color:white;" aria-hidden="true"></i><span class="text"> test</span></a></li>
<li><a href="#"><i class="fa fa-star" style="font-size:15px;color:white;" aria-hidden="true"></i><span class="text"> test</span></a></li>
<li><a href="#"><i class="fa fa-gears" style="font-size:15px;color:white;" aria-hidden="true"></i><span class="text"> test</span></a></li>
</ul>
</li>
</ul>
</div>
</div>

使用setCookie函数创建Cookie,并使用getCookie取值。

function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

JQuery示例

//To set a cookie
$.cookie('the_cookie', 'the_value');
//Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });
//Create expiring cookie, valid across entire page:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
//Read cookie
$.cookie('the_cookie'); // => 'the_value'
$.cookie('not_existing'); // => null
//Delete cookie by passing null as value:
$.cookie('the_cookie', null);
// Creating cookie with all availabl options
$.cookie('myCookie2', 'myValue2', { expires: 7, path: '/', domain: 'example.com', 
secure: true, raw: true });

使用LocalStorage。如果您在本地存储项中保存了一些内容,则cookie会在关闭浏览器时消失,并在刷新页面时保留。

最新更新