css variables

css中variables:css变量

平时没少用sass、less、stylus预编译语言,里面的变量很常见,但都需要前把变量都以静态的方式定义好才能使用,然后编译完后生效,无法和js交互。

variables提供了css与js交互的机会!

一、css变量的定义及使用方式:

/* 
    定义:--开头  有作用域
    */
:root{
    --color1:red;
    --color2:green;
}
.box{
    width:100px;
    height:100px;
}
/* 
    使用:var(css变量)
*/
.box1{
    background-color: var(--color1);
}
.box2{
    background-color: var(--color2);
}
<div class="box1 box"></div>
<div class="box2 box"></div>

效果:

 响应式:

div {
  --color: #7F583F;
  --bg: #F7EFD2;
}

.mediabox {
  color: var(--color);
  background: var(--bg);
}

@media screen and (min- 768px) {
  .mediabox {
    --color:  #F7EFD2;
    --bg: #7F583F;
  }
}

默认值:

var(变量,默认值)

background-color: var(--color1,blue);

设置变量数值:

这样是错误的:

--size: 30;   
font-size: var(--size)px;//不生效

正确方式:

--size: 30px;   
font-size: var(--size);//生效

可以用calc计算:

--size: 30;   
font-size: calc(var(--size) * 1px);//生效

如果变量值带有单位,就不能写成字符串:

/* 无效 */
.divbox {
    --size: '30px';
    font-size: var(--size);
}

/* 有效 */
.divbox {
    --size: 30px;
    font-size: var(--size);
}

图片地址,如url(var(--image-url)) ,不会生效

兼容性处理:

css:

/*css*/

@supports ( (--a: 0)) {
    /* supported */
  .box{xxx:xxx}
} @supports ( not (--a: 0)) { /* not supported */ }

js:

// Js

if (window.CSS && window.CSS.supports && window.CSS.supports('--a', 0)) {
    console.log('CSS properties are supported');
} else {
    console.log('CSS properties are NOT supported');
}

js操作变量:

//读取
let computedStyle = getComputedStyle(document.getElementById("box"));
console.log(computedStyle.getPropertyValue('--bg'));//red
// 写入
document.getElementById("box").style.setProperty('--color1','blue');
// 删除
document.getElementById("box").style.removeProperty('--color1');

原文地址:https://www.cnblogs.com/fqh123/p/15110468.html