网站的护眼模式和夜间模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41179401/article/details/85248304

                                网站的护眼模式和夜间模式

不采用数据库存储字段的方式,而采用cookie来判断是哪种模式

如果会使用js对cookie进行赋值,取值,删除,也可以只用js做

护眼模式图示:

1 给按钮绑定事件

<li class="layui-nav-item">
     <button class="layui-btn layui-btn-primary" onclick="eye(this)" id="eye">开启护眼模式</button>
  </li>

2 js事件:点击根据innerHTML的值传递不同的‘type’值

function eye(obj){
	if(obj.innerHTML=='开启护眼模式'){
		$.post(ThinkPHP['ROOT']+'/index.php/index/index/eye',{'type':'open'},function(res){
			if(res.code==1){
				$('#header').css('background','#C7EDCC');
				$('body').css('background','#C7EDCC');
				obj.innerHTML='关闭护眼模式';
			}
		},'json')
	}else if(obj.innerHTML=='关闭护眼模式'){
		$.post(ThinkPHP['ROOT']+'/index.php/index/index/eye',{'type':'close'},function(res){
			if(res.code==1){
				$('#header').css('background','#fff');
				$('body').css('background','#fff');
				obj.innerHTML='开启护眼模式';
			}
		},'json')
	}
}

3 服务端 根据接收的type值得不同 决定是否生成cookie

//  开启和关闭护眼模式
    public function eye(){
        $type = input('post.type');
        if($type=='open'){
            // 开启护眼 设置cookie
            Cookie('theme','on');
            exit(json_encode(array('code'=>1)));
        }elseif($type=='close'){
            // 关闭护眼 清除cookie
            Cookie::delete('theme');
            exit(json_encode(array('code'=>1)));
        }
    }
    // 判断是不是护眼模式
    public function istheme(){
        if(Cookie::get('theme')){
            exit(json_encode(array('code'=>1)));
        }else{
            exit(json_encode(array('code'=>-1)));
        }
    }

4 回到第二步前端回调函数做出临时的样式改变(但是网站一刷新就会变回来,这样不行)

5 网站一加载就判断是不是护眼模式网站一加载就发送个ajax请求到服务端index控制器下istheme方法,istheme方法是根据网站是否有cookie('theme')来返回不同的数据,前端在根据不同的数据来改变样式

$(function(){
		$.post(ThinkPHP['ROOT']+'/index.php/index/index/istheme',function(res){
			if(res.code==1){
				$('#header').css('background','#C7EDCC');
				$('body').css('background','#C7EDCC');
				$('#eye').html('关闭护眼模式');
			}else{
				$('#header').css('background','#fff');
				$('body').css('background','#fff');
				$('#eye').html('开启护眼模式');
			}
		},'json')
	})

猜你喜欢

转载自blog.csdn.net/qq_41179401/article/details/85248304