格式如下
<!-- 1.给要更改的css加一个标记app -->
<link rel="stylesheet" type="text/css" app>
// 2.用这句来更改css文件
$('link[app]').attr('href', CSS文件路径)
示例代码如下
/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Login</title>
<link rel="stylesheet" href="">
<link rel="stylesheet" href="//static.class4ever.com/layui/v2.5.5/css/layui.css">
<link rel="stylesheet" type="text/css" app><!-- 1.给要更改的css加一个标记app -->
</head>
<body>
<div style="text-align: right;padding-right:100px;padding-top:10px;">
<button class="btn-change layui-btn layui-btn-danger">切换样式</button>
</div>
<div class="login">
<div class="login-title">
后台登录
</div>
<div class="login-form">
<div>
<input type="text" class="layui-input" placeholder="用户名">
</div>
<div>
<input type="password" class="layui-input" placeholder="密码">
</div>
<div>
<button type="button" class="layui-btn layui-btn-fluid layui-btn-normal">登录</button>
</div>
</div>
</div>
</body>
<script src="//static.class4ever.com/layui/v2.5.5/layui.all.js"></script>
<script src="//static.class4ever.com/jquery/jquery-3.4.1.min.js"></script>
<script>
var style = true
useCss()
//监听:点击切换按钮
$('.btn-change').click(function(){
style = !style
let cssFile = useCss()
layer.msg(`css文件已切换为: ${cssFile}`)
})
//切换css文件实操
function useCss(){
let cssFile = style ? 'blue.css' : 'dark.css'
$('link[app]').attr('href', cssFile)//2.用这句来更改css文件
return cssFile
}
</script>
</html>
/blue.css
* {
margin:0;
padding:0;
}
html{
background: #2d3a4b;
}
.login{
width:440px;
height:375px;
margin: 150px auto 0;
}
.login-form{
padding: 0 40px;
}
.login-form>div{
margin-bottom:30px;
}
.login-title{
color:#eee;
font-weight: 900;
font-size:26px;
text-align: center;
margin:50px 0 40px;
}
.login-form input{
border-radius: 5px;
height:47px;
background: #283443;
color:#fff;
border:1px solid #3e4957;
font-size:16px;
}
.login-form input::placeholder{
color:#eee;
}
/dark.css
* {
margin:0;
padding:0;
}
html{
background: #444;
}
.login{
width:440px;
height:375px;
background:#fff;
position: fixed;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
margin: auto;
border-radius: 5px;
}
.login-form{
padding: 0 40px;
}
.login-form>div{
margin-top:30px;
}
.login-title{
font-size:26px;
text-align: center;
margin-top:50px;
}