首页 > 代码库 > jquery cookie插件轻松实现切换背景颜色
jquery cookie插件轻松实现切换背景颜色
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>更换背景颜色</title>
<style type="text/css">
#bg{width: 90%;height: 500px;background: rgba(0,0,0,.2);position: fixed;bottom: 10px;left: 0;right: 0;margin:auto;display: none;border: 5px solid #fff;}
.close{width: 30px;height: 30px;border: 2ps solid;line-height: 30px;text-align: center;color: #fff;background: #000;position: absolute;right: 0;top: 0;font-size: 25px;}
.color{width: 200px;height: 100px;border: 1px solid #fff;float: left;margin:20px 35px;line-height: 100px;text-align: center;color: #fff;font-size: 30px;}
</style>
<script src="http://www.mamicode.com/jquery-1.12.4.js"></script>
<script src="http://www.mamicode.com/jquery.cookie.js"></script>
<script type="text/javascript">
$(function(){
var bgcolor = $.cookie(‘bgcolor‘); //从cookie中读取背景颜色
if(bgcolor){
document.body.style.backgroundColor = bgcolor; //显示cookie中已经存在的颜色
$(‘#bg‘).css(‘backgroundColor‘,‘rgba(255,255,255,.7)‘); //将id为bg的div背景色改为半透明的白色
}
$(‘#btn‘).on(‘click‘,function(){
$(‘#bg‘).show();
});
$(‘.close‘).on(‘click‘,function(){
$(‘#bg‘).hide();
});
//获取class为color的元素,并设置背景色
$(‘.color‘).each(function(index,element){
var bgcolor = $(element).text();
$(this).css(‘backgroundColor‘,bgcolor);
$(element).on(‘click‘,function(){
document.body.style.backgroundColor = bgcolor;
$.cookie(‘bgcolor‘,bgcolor,{‘expires‘:30,‘path‘:‘/‘});
});
});
});
</script>
</head>
<body>
<button id="btn">切换皮肤</button>
<div id="bg">
<span class="color">green</span>
<span class="color">red</span>
<span class="color">yellow</span>
<span class="color">blue</span>
<span class="color">lightgreen</span>
<span class="color">pink</span>
<span class="color">orange</span>
<span class="color">gold</span>
<span class="color">purple</span>
<strong class="close">×</strong>
</div>
</body>
</html>
本文出自 “11996687” 博客,请务必保留此出处http://12006687.blog.51cto.com/11996687/1862133
jquery cookie插件轻松实现切换背景颜色