前期回顾
你把 css:hover 玩明白_0.活在风浪里的博客-CSDN博客你想要什么hover效果?你想要什么动画?十万行不同动画效果,可单独复制出来几行使用,极简轻量,css奇淫技巧还在等待什么,99+种功能,总能满足你的要求,快来一键三连抱走吧https://blog.csdn.net/m0_57904695/article/details/126309518?spm=1001.2014.3001.5501 比如你写一个网站大量用到相同的颜色,就可以使用css自定义属性
--正式开始
/*
Tip: 变量的名称可以用数字、汉字等,不能包含$,[,^,(,%**等字符,变量的值也是可以使用各种属性值:
:root相当于html根元素,可以用来设置根元素的属性,如::root{--color:red;}
定义语法: --自定义样式名:值;
使用语法: 样式属性名称:var(--变量名);
*/
1: 基本例子
<style>
:root {
/*全局样式可复用*/
--红色背景: #ff0000;
--39: rgb(39, 214, 16);
--pd: 10px 20px;
--height: 200px;
}
.box {
width: 100px;
background: var(--红色背景);
height: var(--height);
color: var(--39);
padding: var(--pd);
}
.box1 {
width: 100px;
height: var(--height);
padding: var(--pd);
/*可复用*/
background: var(--红色背景);
margin: 10px;
}
</style>
<body>
<div class="box">红色</div>
<div class="box1">1</div>
</body>
2: var()第二个参数
你使用的自定义属性没定义,所以控制台没有背景色,
此时你可以借助var第二个参数,
如果第一个参数引用的自定义属性无效,则该函数将使用第二个值。
3:JavaScript获取css变量
第一种
<style>
:root {
--如何得到富婆的芳心: pink;
--width: 100px;
--height: 200px;
}
.box {
width: var(--width);
height: var(--height);
background: var(--怎么让富婆爱上我, red);
}
</style>
<body>
<div class="box">666</div>
</body>
<script>
let b = document.querySelector('.box');
b.style.backgroundColor = 'green';
</script>
第二种
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
/* 在这里定义变量 */
:root {
--var-primary-color: red;
--var-cyan-color: blue;
}
.box {
width: 200px;
height: 200px;
/* 通过 var(变量名) 引入变量即红色 */
background: var(--var-primary-color);
}
</style>
</head>
<body>
<div class="box"></div>
<button onclick="onChange()">改变颜色</button>
<script type="text/javascript">
// 改变颜色
function onChange()
{
// 通过 setProperty 函数将其 --var-primary-color 变量更改为绿色
// document.documentElement.style.setProperty('--var-primary-color', 'green')
// 你也可以用 var(--var-cyan-color) 的方式传递进去,它会自动转成对应的 blue
document.documentElement.style.setProperty('--var-primary-color', 'var(--var-cyan-color)')
}
</script>
</body>